Created
June 6, 2023 08:49
-
-
Save Risyandi/6ba822b1f55238a6e2657b44d910db6b to your computer and use it in GitHub Desktop.
convert text string to tsnake case, and remove special character by condition.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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