Search code examples
javascriptregexunderline

Which symbol matches "underline" in Regex in Js


str = "The stor-+)_y is someth12ing that tr@#ee3 de124scrib%^&ing 
becom5es life7 4 difficult";
console.log(str.replace(/\W/g,''));

Guys, have written this RegEx for matching all non alphanumeric characters, but cannot select 'underline' ? As I know, \d is for all digits \s for whitespace... so, what letter stand for underline?


Solution

  • To match all non-alphanumeric characters, \W is not enough since matches the same text as [^a-zA-Z0-9_] does. To match _ with your regex, add _ and \W to a character class:

    str = "The stor-+)_y is someth12ing that tr@#ee3 de124scrib%^&ing becom5es life7 4 difficult";
    console.log(str.replace(/[\W_]+/g,''));

    Since you are removing, it is advisable to quantify with + (to remove 1+ consecutive occureences in one go).