본문 바로가기
Research/Javascript

Regex_replacing special chrs and space

by RIEM 2023. 9. 22.

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

댓글