[英]Regular Expression from String gives null in Javascript
I have a string我有一个字符串
let str = 'WordA<br>WordB';
I am using this expression /(\\S+)(?=<br>)/
to match characters before the <br>
.我使用这个表达式
/(\\S+)(?=<br>)/
来匹配<br>
之前的字符。
It works fine directly as a predefined function它可以直接作为预定义函数正常工作
let regex = /(\\S+)(?=<br>)/;
But when I try to build it using a string, it gives null
everytime.但是当我尝试使用字符串构建它时,它每次都会给出
null
。
let rgs = "(\S+)(?=<br>)";
let regex = new RegExp(rgs);
How to use the regex as a string to obtain the same results.如何使用正则表达式作为字符串来获得相同的结果。
Full code:完整代码:
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]);
When using regex in string via new RegExp()
, you need to escape the backslash character:通过
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]);
Otherwise the "\\S"
is translated to just "S" (as you are escaping the S
character):否则,
"\\S"
被转换为“S”(因为您正在转义S
字符):
console.log("S", "\\S", "\\\\S", "S" === "\\S");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.