Skip to content

Instantly share code, notes, and snippets.

@Risyandi
Created June 6, 2023 08:49
Show Gist options
  • Save Risyandi/6ba822b1f55238a6e2657b44d910db6b to your computer and use it in GitHub Desktop.
Save Risyandi/6ba822b1f55238a6e2657b44d910db6b to your computer and use it in GitHub Desktop.
convert text string to tsnake case, and remove special character by condition.
function convertToSnakeCase(text) {
let snakeCaseText = "";
const specialChars = `!"#$%&'()*+,-./:;<=>?@[\\]^\`{|}~`;
for (let index = 0; index < text.length; index++) {
const char = text[index];
if (char === "_" || char === " ") {
snakeCaseText += "_"; // Preserve underscores and change spaces to underscores
} else if (!specialChars.includes(char)) {
snakeCaseText += char; // Append alphanumeric characters
}
}
return snakeCaseText.toLowerCase();
}
// Example usage
console.log(convertToSnakeCase("Can123'''not move session to state \\\"open\\\" from state \\\"closed\\\"_UA"));
// Output: "cant_assign_users_to_expired_coupon_ua"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment