我对正则表达式不太熟悉。我试图测试一个字符串是否以另一个字符串结尾。当我期望 true 时,下面的代码返回 null。代码有什么问题?
var id = "John";
var exists ="blahJohn".match(/id$/);
alert(exists);
最佳答案
好吧,通过这种方法,您需要使用 RegExp
constructor ,使用 id
变量构建正则表达式:
var id = "John";
var exists = new RegExp(id+"$").test("blahJohn");
alert(exists);
但是有很多方法可以实现这一点,例如,您可以获取字符串的最后一个 id.length
字符,并将其与 id
进行比较:
var id = "John";
var exist = "blahJohn".slice(-id.length) == id; // true
关于javascript - 正则表达式字符串以在 Javascript 中不起作用为结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4996033/