我有一个字符串
let str = 'WordA<br>WordB';
我正在使用这个表达式/(\S+)(?=<br>)/
匹配 <br>
之前的字符.
它可以直接作为预定义函数正常工作
let regex = /(\S+)(?=<br>)/;
但是当我尝试使用字符串构建它时,它给出 null
每次。
let rgs = "(\S+)(?=<br>)";
let regex = new RegExp(rgs);
如何使用正则表达式作为字符串来获得相同的结果。
完整代码:
let str = 'WordA<br>WordB';
let regex = /(\S+)(?=<br>)/;
let m = str.match(regex);
console.log(m);
console.log(m[1]);
let rgs = ("(\S+)(?=<br>)");
let regex2 = new RegExp(rgs);
let m2 = str.match(regex2);
console.log(m2);
console.log(m2[1]);
最佳答案
当通过new RegExp()
在字符串中使用正则表达式时,需要转义反斜杠字符:
let str = 'WordA<br>WordB';
let regex = /(\S+)(?=<br>)/;
let m = str.match(regex);
console.log(m);
console.log(m[1]);
let rgs = "(\\S+)(?=<br>)";
let regex2 = new RegExp(rgs);
let m2 = str.match(regex2);
console.log(m2);
console.log(m2[1]);
否则,"\S"
将被转换为“S”(因为您正在转义 S
字符):
console.log("S", "\S", "\\S", "S" === "\S");
关于javascript - 字符串中的正则表达式在 Javascript 中给出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46998765/