I´m replacing weird characters with ""
but I have two scenarios that are not covered.
strings can contain multiple spaces (only one should be allowed) and underscore (, _)
"this_is_my_string".replace(/[^\w\s]/gi, "");
how to tweak it to cover those scenarios?
examples
this_is_my_string => thisismystring
this is my string => this is my string
this is my string => this is my string
I think what you really want is this regex:
value.replace(/_|[^\w\s*]|\s{1,}/g,"");
The _|
any character that matches _
[OR] [^
(Negated nest): will match any character that not in the set which is: \w\s*
word, whitespace, 0 or more instances of the preceding regex token. ]|
exiting the negated nest. [OR] \s{2}
, 2 white spaces
var test = [ 'this_is_my_string', 'this is my string', 'this is my string', 'this%$is my@@@string', ]; console.log(test.map(function(a) { return a.replace(/(\s)+|[\W_]/g, "$1"); }));
you could try being more specific with the words part and instead match on the characters, the for the spacing you could just look for more than one space.
[^A-Za-z\s]|\s{2,}
You can try this regex:
/[ \t]{2,}|[\_]/
It will select two or more spaces and underscores.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.