简体   繁体   English

为什么正则表达式在表单输入上不正确。 Javascript

[英]Why is the regex not correct on form inputs. Javascript

In my contactform, I added event listeners that are looking for url strings in the input fields.在我的联系表单中,我添加了在输入字段中寻找 url 字符串的事件侦听器。 I'm using the regex (http:|https:|www|\/\/|\\\\)+ to do the job.我正在使用正则表达式(http:|https:|www|\/\/|\\\\)+来完成这项工作。 All strings in the regex are working fine, except \\\\ will give a hit on 1 backslash.正则表达式中的所有字符串都工作正常,除了\\\\会在 1 个反斜杠上命中。

Why is the regex ok on https://regexr.com and why is it not working in Javascript?为什么正则表达式在https://regexr.com上正常,为什么它在 Javascript 中不起作用?

jsFiddle https://jsfiddle.net/j3hsvapm/1/ jsFiddle https://jsfiddle.net/j3hsvapm/1/

What am I doing wrong?我究竟做错了什么?

SOLVED because Opera does not support the String.raw I used 8 backslashes as recommended by @user120242, and now it is working fine.解决,因为 Opera 不支持String.raw我使用了 @user120242 推荐的 8 个反斜杠,现在它工作正常。

 var formElms = document.querySelectorAll('.testme'); Object.keys(formElms).forEach(function(key) { formElms[key].addEventListener('input', function () { var result = 'OK'; var reg = new RegExp("(http:|https:|www|\/\/|\\\\\\\\)+", "gi"); value = formElms[key].value; // console.log(key, ': ', value); if (reg.test(value)) result = 'Not allowed'; document.querySelector('#result').innerHTML = result; }); });
 div, input, textarea { width: 200px; font: 400 16px/1.5 sans-serif; }
 <div id="result">OK</div> <br><input class="testme" type="text"> <br><br><textarea class="testme" rows="4"></textarea>

Due to string escaping:由于字符串 escaping:
"\\\\" turns into the string \\ and then regex escapes again so it becomes \ "\\\\"变成字符串\\然后正则表达式再次转义,所以它变成\

A few solutions:几个解决方案:

  • new RegExp("(http:|https:|www|\\/\\/|\\\\\\\\)+","gi") (8 backslashes) new RegExp("(http:|https:|www|\\/\\/|\\\\\\\\)+","gi") (8 个反斜杠)
  • /(http:|https:|www|\/\/|\\\\)+/gi (regex literal) /(http:|https:|www|\/\/|\\\\)+/gi (正则表达式文字)
  • (template literal and String.raw) (模板文字和 String.raw)
    new RegExp(String.raw`(http:|https:|www|\/\/|\\\\)+`,'gi')

The last one is probably the most elegant solution, and will fit your need to use variable substitution.最后一个可能是最优雅的解决方案,并且适合您使用变量替换的需要。 eg:例如:

myvar = "somestring"
console.log(new RegExp(String.raw`^http://${myvar}$`,'gi').test('HTTP://SOMEstring'))

Note: OP has pointed out that Opera lacks String.raw support注意:OP 指出 Opera 缺乏对 String.raw 的支持
For those who want to be able to use String.raw, and are using babeljs , there is a plugin for String.raw support:babel-plugin-transform-string-raw对于那些希望能够使用 String.raw 并且正在使用babeljs的人,有一个支持 String.raw 的插件:babel-plugin-transform-string-raw
Sample transpilation online demo 样本转译在线演示

Using regex literal syntax instead:改用正则表达式文字语法:

 var formElms = document.querySelectorAll('.testme'); Object.keys(formElms).forEach(function(key) { // console.log(key, formElms[key], formElms[key].value); formElms[key].addEventListener('input', function () { var result = 'OK'; var reg = /(http:|https:|www|\/\/|\\\\)+/gi; value = formElms[key].value; console.log(key, ': ', value); if (reg.test(value)) result = 'Not allowed'; document.querySelector('#result').innerHTML = result; }); });
 div, input, textarea { width: 200px; font: 400 16px/1.5 sans-serif; }
 <div id="result">OK</div> <br><input class="testme" type="text"> <br><br><textarea class="testme" rows="4"></textarea>

Demo that shows what is happening with the string escaping.演示显示字符串 escaping 发生的情况。 Note: In regex \\ matches on the escaped \ character注意:在正则表达式中\\匹配转义的\字符
And showing how you can use String.raw template tag and template literals to avoid string escaping:并展示如何使用String.raw 模板标签模板文字来避免字符串 escaping:

 str = "(http:|https:|www|\/\/|\\\\)+" console.log("str: ",str) // notice that you get \\ re = new RegExp(str,"gi") console.log(re) console.log(re.source) // using template string syntax and the "raw" template tag str = String.raw`(http:|https:|www|\/\/|\\\\)+` console.log("raw str: ",str) re = new RegExp(str,"gi") console.log(re) console.log(re.source)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从表单输入中乘以2个矩阵。 (JavaScript)的 - multiply 2 matrices from form inputs. (Javascript) 使用removeChild删除多个表单输入时出错。 - Error when using removeChild to remove multiple form inputs. 具有多个输入的表单。 显示/隐藏 label 用于输入是否填充 - Form with multiple inputs. Show/hide label for input if filled or not 立即实现其他输入。 jQuery,Javascript解决方案 - Instantly actualize other inputs. jQuery , Javascript Solution JS-&gt;对输入的表单验证。 使用for循环获取所有输入索引 - JS->Form validation on inputs. Using for loop to get all the inputs index 有人能告诉我为什么它在控制台中没有显示任何内容吗? 我想获得输入值。 我必须使用表格吗? - Can someone tell me why it doesn't show anything in console?? I want to get values of inputs. Do I have to use form? 我想使用无线电输入的文本。 我如何使用 jQuery 或 JavaScript 获得它 - I want to use the text of radio inputs. How can i get it using jQuery or JavaScript 如何重复 JavaScript 表单验证,直到所有输入正确,然后将输入插入数据库? - How can I repeat JavaScript form validation until all inputs are correct, then insert the inputs in the database? 使用 Javascript 验证表单输入 - Validate Form Inputs With Javascript 验证JavaScript中的表单输入 - validation of form inputs in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM