Javascript matching “\” backslash in a string [closed]

旧巷老猫 提交于 2019-12-06 08:21:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!