Javascript正则表达式对象和美元符号 [英] Javascript Regex object and the dollar symbol

查看:283
本文介绍了Javascript正则表达式对象和美元符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中。我期待的是真的,但我却变得虚假了。我错过了什么?

In the code below. I expected true but i am getting false instead. What am I missing?

var text = "Sentence $confirmationlink$ fooo";     
alert(placeHolderExists(text,'confirmationlink'); // alerts false
function placeHolderExists(text,placeholdername) {  
  var pattern = new    RegExp('\$'+placeholdername+'\$');    
  return pattern.test(text);
}


推荐答案

在构建字符串时,RegExp表达式构建器中的\被视为转义字符,就像在实际的RegExp中一样。您需要转义两次,尝试:

The "\" in the RegExp expression builder is treated as an escape character when building the string, just as it is in the actual RegExp. You need to escape twice, try:

new RegExp('\\$'+placeholdername+'\\$');

这篇关于Javascript正则表达式对象和美元符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆