javascriptregex

Remove Special Character Javascript


Currently I try this expression /[^\w\s]/gi in javascript. However, it doesn't remove _ underscore. How to remove underscore? I want to remove these special characters !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

var text = reasonTxt.GetText(); var textFull = text.replace(/[^\w\s]/gi, ''); 

Solution

  • _ is considered as word character. so you need to negate this also.

    var text = reasonTxt.GetText(); var textFull = text.replace(/[^\w\s]|_/gi, '');
    

    Demo

    let str = "vivek #$ asbc &12341236~!@#$%^&   _    !#$%&'()*+,-./:;<=>?@[]^_`{|}~+_";
    
    
    
    console.log(str.replace(/[^\w\s]|_/gi, ""));