问题
I am using below code to match words in a comma separated string
<script>
var str="testdata, W3\standard,";
var patt=/\bW3\\standard/g;
document.write(str.match(patt) );
</script>
But it does not give me result even though i escape the string in regular expression. Any help on this
回答1:
The string doesn't have a \
character in it since that starts an escape sequence when you use it in string literals.
You have to escape the character in your original string literal:
var str="Don't visit the awful W3\\Schools,";
var patt1=/\bW3\\Schools/g;
document.write(str.match(patt1));
回答2:
There's no backslash in the string. You need to escape it in the string literal, too:
var str="Visit, W3\\Schools,";
// here ----------^
来源:https://stackoverflow.com/questions/16394693/javascript-matching-backslash-in-a-string