I have the following code:
JavaScript
x
8
1
ttt = 'hello---,,..there';
2
tt2 = strip(ttt);
3
alert(tt2);
4
5
function strip(str){
6
return str.replace(/[^a-zA-Z0-9 ,.-_]/g, '');
7
}
8
The alert gives hello,,..there
I would expect it to give hello---,,..there
as all the characters, including hyphens, are specified as exceptions in the replacement function.
What am I doing wrong?
Advertisement
Answer
Escape the hyphen:
JavaScript
1
2
1
'hello---,,..there'.replace(/[^a-zA-Z0-9 ,.-_]/g, ''); // => "hello---,,..there"
2