regex - javascript replace() function strange behaviour with regexp -
am doing sth wrong or there problem js replace ?
<input type="text" id="a" value="(55) 55-55-55" /> document.write($("#a").val().replace(/()-/g,'')); prints (55) 555555 how can replace () , spaces too?
in javascript regular expression, ( , ) characters have special meaning. if want list them literally, put backslash (\) in front of them.
if goal rid of (, ), -, , space characters, character class combined alternation (e.g., either-or) on \s, stands "whitespace":
document.write($("#a").val().replace(/[()\-]|\s/g,'')); (i didn't put backslashes in front of () because don't need within character class. did put 1 in front of - because within character class, - has special meaning.)
alternately, if want rid of anything isn't digit, can use \d:
document.write($("#a").val().replace(/\d/g,'')); \d means "not digit" (note it's capital, \d in lower case opposite [any digit]).
more info on mdn page on regular expressions.
Comments
Post a Comment