[英]using a variable with refer and matching to an array
Hello I have an input that validates if a string is unique.您好,我有一个输入可以验证字符串是否唯一。 I have an array of already current values to check against.我有一组已经存在的值来检查。 If the user inputs in all capitals I want it to still match as long as it's exact.如果用户输入所有大写,我希望它仍然匹配,只要它是精确的。 I tried doing a new regex constructor but there is no flag for returning only exact matches.我尝试做一个新的正则表达式构造函数,但没有仅返回完全匹配的标志。
Here is what I have which returns dog and doggy.这是我拥有的返回狗和小狗的东西。 I just want dog.我只想要狗。
let myarray = [‘dog’ , ‘doggy’, ‘cat’]
let value = ‘dog’
let reg = new RegExp(value, 'i');
let tag = myarray.filter(function (str) { return reg.test(str); });
To find an exact word, add the matches beginning ( ^
sign) before the value, and matches end ( $
sign) after the value:要查找确切的单词,请在值之前添加开头( ^
符号)的匹配项,并在值之后匹配结尾( $
符号):
const myarray = ['dog', 'doggy', 'cat'] const value = 'dog' const reg = new RegExp(`^${value}$`, 'i'); const tag = myarray.filter((str) => reg.test(str)); console.log(tag);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.