在正则表达式javascript中转义问号
我认为这是一个简单的问题。
我正在尝试使用 JavaScript 中的正则表达式在另一个字符串中搜索字符串的出现,如下所示:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
由于 ?
字符,这不起作用......我尝试使用 转义它\
,但这也不起作用。 是否有另一种方法可以按字面意思使用 ?
而不是作为特殊字符?
This is a simple question I think.
I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:
var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";
var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");
if(content.search(gent) != -1){
alert('worked');
}
This doesn't work because of the ?
character....I tried escaping it with \
, but that doesn't work either. Is there another way to use ?
literally instead of as a special character?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要用两个反斜杠对其进行转义,
请参阅以下内容了解更多详细信息:
http ://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You need to escape it with two backslashes
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
你应该使用双斜杠:
为什么? 因为在 JavaScript 中
\
也用于转义字符串中的字符,所以:“\?” 变为:"?"
并且
"\\?"
变为"\?"
You should use double slash:
Why? because in JavaScript the
\
is also used to escape characters in strings, so: "\?" becomes:"?"
And
"\\?"
, becomes"\?"
您可以使用斜杠而不是引号来分隔正则表达式,然后使用单个反斜杠来转义问号。 尝试这个:
You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:
每当您有已知模式(即您不使用变量来构建正则表达式)时,请使用文字正则表达式表示法,其中您只需要使用单个 em> 反斜杠来转义特殊的正则表达式元字符:
每当您需要动态构建 RegExp 时,请使用
RegExp
构造函数表示法,其中必须双反斜杠来表示文字反斜杠:如果您使用
String.raw
字符串文字,您可以按原样使用\
(请参阅使用模板字符串文字的示例,您可以在其中放置变量进入正则表达式模式):必读:RegExp:说明< /em> 在 MDN。
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
Whenever you need to build a RegExp dynamically, use
RegExp
constructor notation where you MUST double backslashes for them to denote a literal backslash:And if you use the
String.raw
string literal you may use\
as is (see an example of using a template string literal where you may put variables into the regex pattern):A must-read: RegExp: Description at MDN.