[英]Check if a string contains a specific word only once
我正在尝试检查一个字符串是否只包含一次特定的单词。
这是我的尝试,但它不起作用:
const test = "hello this is a new string hello"; // if hello contains only once then true otherwise false; // here is my try but let containshello = test.includes("hello"); console.log(containshello);
这是一种使用过滤器的方法
const containsWordOnce = (str, searchKey) => { return str.split(' ').filter((word) => word === searchKey).length === 1; }; const test = "hello this is a new string hello"; console.log(containsWordOnce(test, "hello"));
使用“正则表达式匹配”来获取 substring 在字符串中的出现。
const test = "hello this is a new string hello";
console.log(test.match(/hello/gi)?.length); // 2 : 'hello' two times
console.log(test.match(/new/gi)?.length); // 1 : 'new' one time
console.log(test.match(/test/gi)?.length); // undefined : 'test' doesn't exist in string.
我使用“g”进行全局检查,使用“i”忽略大小写。
如果要创建“正则表达式”object,请像这样创建:
const test = "hello this is a new string hello";
const regx = new RegExp('hello', 'gi') // /hello/gi
console.log(test.match(regex)?.length);
const test = "hello this is a new string hello"; const findString = "hello" console.log(test.split(findString).length-1 === 1)
我只想使用正则表达式,并使用“i”和“g”标志对要搜索的字符串使用 match 方法。 下面是一个示例 function 尽管很可能有更好的方法。
function containsWordOnce(string, word) {
const re = new RegExp(word, 'ig');
const matches = string.match(re);
return matches.length === 1;
}
只需插入您要查找的字符串和单词即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.