RegExpリテラルと文字列の使用に違いはありますか?JavaScript RegExp:異なる結果:文字列を使用し&regexp "literal"を使用してパターンを作成しましたか?
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
オブジェクトを使用している場合でも、私はまだ同じ結果を得る