javascript 将正则表达式字符串转换为类型对象

标签 javascript

我有一个框,用户在其中输入正则表达式,在 Javascript 中,我采用该值并用它测试另一个字符串,如下所示:(这是我真正问题的抽象)

var regex = $('input').val();
regex.test('some string');

我知道确保将 regex 转换为安全的 Object 类型的唯一方法是使用 eval()

这是最好的转换方式吗?

最佳答案

使用 RegExp 构造函数创建模式。

// The next line would escape special characters. Since you want to support
//    manually created RegExps, the next line is commented:
// regex = regexp.replace(/([[^$.|?*+(){}])/g, '\\$1')

regex = new RegExp(regex);
//                      ^ Optionally, add the flags as a second argument, eg:
//regex=new RegExp(regex, 'i');   //Case-insensitive

更新
您似乎误解了 RegExp 构造函数的用法。 “斜杠符号”是创建正则表达式的“原始”方式。为了进行比较,请考虑(new 是可选的):

"123"             ===    new String(123)
false             ===    new Boolean(1)
// Because a RegExp is an object, the strict compare `===` method evaluates to
//  false if the pattern is not the same object.
// Example:   /\d/ == /\d/   evaluates to false
//      To compare a regex pattern, use the `pattern` property
/[a-z]/i.pattern   ===    (new RegExp("[a-z]", "i")).pattern

RegExp 构造函数采用两个参数,第二个参数是可选的:

  1. 字符串 模式(没有尾部和结尾斜杠)
  2. 字符串(可选) 标志组合:

    • i(忽略大小写)
    • g(全局匹配)
    • m(多行(很少使用))。

示例(new 是可选的):

Using constructor                 using slash-notation   # Notice:
RegExp('[0-9]');                /[0-9]/                  # no slashes at RegExp
RegExp('/path/to/file\.html$')  /path\/to\/file\.html$/  # the escaped \ 
RegExp('i\'m', 'i')             /i'm/i                   # \' vs ', 'i' vs /i

使用斜杠符号实现“RegExp”表单字段

var regex = $('input').val();  //Example: '/^[0-9]+$/i'
// Using a RegEx to implement a Reg Exp, ironically..
regex = regex.match(/^\/([\S\s]+)\/([gim]{0,3})$/);
regex = regex || [, regex, ""];        // If the previous match is null,
                                     // treat the string as a slash-less RegEx
regex = new RegExp(regex[1], regex[2]);
regex.test('some string');

关于javascript 将正则表达式字符串转换为类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429620/

相关文章:

javascript - jQuery ajax post请求不发送数据

JavaScript 将 css 添加到动态表格单元格

javascript - 要在幻灯片外显示的 slider 标题

javascript - 按钮单击不以弹出窗口形式触发

Javascript 前进后退按钮

javascript - D3 图表似乎超出了 x 轴(画笔效果的裁剪问题)

javascript - 如何重置 three.js 时钟?

javascript - 具有 'slidedown' 功能的横幅广告在我的 jsfiddle 中有效,但在真实环境中无效

javascript - "click"在 "fadeOut"之后立即触发?

javascript - 无法解决我的 Express 应用中的 CORS 政策