gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:13:24 25 4
gpt4 key购买 nike

我有一个用户输入正则表达式的框,在 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. 字符串(可选) Flags 组合:

    • 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com