我需要从用户输入字符串创建一个正则表达式。这是我的代码。我输入了 id 'regex'。
<input id='regex'/>
这是我的 js 代码。
var regex = $('#regex').val();
regexp = new RegExp(regex);
testString = "foo is bar";
alert(testString.replace(regexp, ''));
但是,如果我添加 //g 作为示例来删除字符串中的空格,则它不起作用。我将其作为正则表达式
/\/ \/g/
有没有办法将其转换为与我的字符串完全一样的正则表达式?
最佳答案
如果用户将 /
放在模式的每一侧,后跟单词字符和右侧字符串的末尾,则在传递给 new RegExp
之前解析它们>,并将单词字符作为第二个参数传递:
$('#regex').on('change', () => {
const input = $('#regex').val();
const match = input.match(/^\/(.*)\/(\w+)$/);
const pattern = match
? new RegExp(match[1], match[2])
: new RegExp(input);
console.log(pattern);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='regex'/>
关于javascript - 从正则表达式的字面表示法中删除反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59133627/