简体   繁体   English

当字符串以“ <”字符开头时,jQuery正则表达式不匹配

[英]jQuery regex can't match when string starts with “<” character

I am trying so see if the start of a string has the "<" character, but it will not work. 我正在尝试查看字符串的开头是否具有“ <”字符,但是它将不起作用。 It works fine in regex101.com , but not when I try it in personal files. regex101.com上它可以正常工作 ,但在个人文件中尝试时却不能。

Type in a backslash and it works fine, type in a < and it will not work. 键入backslash ,它可以正常工作,键入< ,它将不起作用。

 $(function() { $(document).on('keyup', '.input', function() { var str = $(this).html(); // not working if (str.match(/^</)) { console.log('starts with "<" character'); } // but this works?? if (str.match(/^\\\\/)) { console.log('starts with backslash'); } }); }); 
 .input { border: 1px solid #ccc; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="input" contenteditable></div> 

Javascript could be encoding the < symbol to &lt; Javascript可以将<符号编码为&lt; . Try doing console.log(str); 尝试做console.log(str); to take a look if this is happening (it did when I tried it in my browser). 看看是否正在发生(我在浏览器中尝试过的情况)。

If that's the case, replace the < symbol with &lt; 如果是这样,请将<符号替换为&lt; in your pattern like so: 像这样:

    if (str.match(/^&lt;/)) {
        console.log('starts with "<" character');
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM