Situation
- Want to create regex to replace all space and special characters except number and alphabets
Solution
function replaceSpecialCharacters(text) {
// Create a regular expression that matches all space and special characters.
const pattern = new RegExp(/[\W_]/g);
// Replace all matches with an empty string.
return text.replace(pattern, "");
}
// Example
const text = "This is a test string. 1234567890";
const replacedText = replaceSpecialCharacters(text);
console.log(replacedText); // Thisisateststring1234567890
[\W_]g
\W
: mean non-word character class
/g
: mean globally all matching
댓글