使用 RegExp 字面值与使用字符串之间有什么区别吗?
String.prototype.lastIndexOf = function(pattern) {
pattern = pattern + "(?![\s\S]*" + pattern + ")";
var match = this.match(pattern);
return (match == null) ? -1 : match.index;
}
function indexOfLastNewline(str) {
var match = str.match(/\r?\n(?![\s\S]*(\r?\n))/);
return (match == null) ? -1 : match.index;
}
var str = "Hello 1\nHello 2\nHello 3\nHello4";
alert(str.lastIndexOf("(\r?\n)")); // always returns the 1st newline (7)
alert(indexOfLastNewline(str)); // returns correctly (23)
更新
即使我使用 RegExp
对象,我仍然得到相同的结果
最佳答案
您需要将字符串版本中的\
转义为\\
,如下所示:
String.prototype.lastIndexOf = function(pattern) {
pattern = pattern + "(?![\\s\\S]*" + pattern + ")";
var match = this.match(pattern);
return (match == null) ? -1 : match.index;
}
function indexOfLastNewline(str) {
var match = str.match(/\r?\n(?![\s\S]*(\r?\n))/);
return (match == null) ? -1 : match.index;
}
var str = "Hello 1\nHello 2\nHello 3\nHello4";
alert(str.lastIndexOf("(\\r?\\n)")); // returns correctly (23)
alert(indexOfLastNewline(str)); // returns correctly (23)
关于JavaScript 正则表达式 : Different results: Built pattern using string & using regexp "literal"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4323456/