JavaScript RegExp:不同的结果:使用字符串 & 构建模式使用正则表达式“文字"? [英] JavaScript RegExp: Different results: Built pattern using string & using regexp "literal"?

查看:47
本文介绍了JavaScript RegExp:不同的结果:使用字符串 & 构建模式使用正则表达式“文字"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 RegExp 文字与字符串之间有什么区别吗?

Is there any differences between using RegExp literals vs strings?

http://jsfiddle.net/yMMrk/

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 对象,我仍然得到相同的结果

even if I use a RegExp object, I still get the same result

http://jsfiddle.net/yMMrk/2/

推荐答案

您需要将字符串版本中的 \ 转义为 \\,如下所示:

You need to escape your \ in the string version as \\, like this:

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 RegExp:不同的结果:使用字符串 & 构建模式使用正则表达式“文字"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆