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

javascript casting a string of regex into a type object

本文关键字:一个 类型 对象 转换 字符串 Javascript 正则表达式      更新时间:2023-09-26

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

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

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

这是最好的cast方式吗?

使用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. String(可选)标志

    • i(忽略大小写)
    • g (global match)
    • 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');

try

var regex = new RegExp( $('input').val() );
相关文章: