边界条件与javascript正则表达式

时间:2017-06-21 14:03:56

标签: javascript regex

假设我在javascript中有一个字符串

var str = if {{SQL}}。Employee.name else {{SQL}}。EmployeeContact.phone

并希望替换{{SQL}}。员工{{SQL}}。Employee1

期望的输出是:

if {{SQL}}。Employee1.name else {{SQL}}。EmployeeContact.phone

但我得到如下输出:

if {{SQL}}。Employee1.name else {{SQL}}。Employee1Contact.phone

下面的

是相同的代码:

<!DOCTYPE html>
<html>
   <body>
      <p>Click the button to replace "blue" with "red" in the paragraph below:</p>
      <p id="demo">if {{SQL}}.EMPLOYEE.name else {{SQL}}.EMPLOYEECONTACT.phone</p>
      <button onclick="myFunction()">Try it</button>
      <script>
         function myFunction() {
             var str = document.getElementById("demo").innerHTML;
             var tr="{{SQL}}.EMPLOYEE"
             var res = str.replace(new RegExp("\\b"+tr+"\\b","g"),"
                   {{SQL}}.EMPLOYEE1");
             document.getElementById("demo").innerHTML = res;
         }
      </script>
   </body>
</html>

1 个答案:

答案 0 :(得分:2)

您描述的问题与示例代码中的问题不同。所描述的问题是缺少字边界。这存在于您的代码中。

代码中的问题是,在表达式之前,您还有字边界 。这应该匹配空格和第一个{之间的位置,并且不符合单词边界。

if {{SQL}}.EMPLOYEE
  ^^ - between these there's no word boundary since neither
       space, nor the opening bracket are word characters.

这是一个工作代码示例,删除了第一个字边界

    <!DOCTYPE html>
    <html>
       <body>
          <p>Click the button to replace "blue" with "red" in the paragraph below:</p>
          <p id="demo">if {{SQL}}.EMPLOYEE.name else {{SQL}}.EMPLOYEECONTACT.phone</p>
          <button onclick="myFunction()">Try it</button>
          <script>
             function myFunction() {
                 var str = document.getElementById("demo").innerHTML;
                 var tr="{{SQL}}.EMPLOYEE";
                 var re = new RegExp( tr + "\\b","g");
                 var res = str.replace(re,"{{SQL}}.EMPLOYEE1");
                 document.getElementById("demo").innerHTML = res;
             }
          </script>
       </body>
    </html>

我也在正则表达式中逃过了一段时间,因为正则表达式中未转义的.匹配任何字符。