Kha*_*111 2 javascript string split
因此,您可以使用 .includes() 方法轻松检查字符串是否包含特定子字符串。
我有兴趣查找字符串是否包含单词。
例如,如果我搜索“on”字符串,“phones are good”,它应该返回 false。并且,它应该为“将其保留在桌子上”返回 true。
Mah*_*Ali 12
您首先需要使用将其转换为数组split(),然后使用includes()
string.split(" ").includes("on")
Run Code Online (Sandbox Code Playgroud)
只需要传递的空白" ",以split()获取所有单词
当您需要解决这些问题时,您可以使用101regex网站(它有帮助)。也带有自定义分隔符的单词。
function checkWord(word, str) {
const allowedSeparator = '\\\s,;"\'|';
const regex = new RegExp(
`(^.*[${allowedSeparator}]${word}$)|(^${word}[${allowedSeparator}].*)|(^${word}$)|(^.*[${allowedSeparator}]${word}[${allowedSeparator}].*$)`,
// Case insensitive
'i',
);
return regex.test(str);
}
[
'phones are good',
'keep it on the table',
'on',
'keep iton the table',
'keep it on',
'on the table',
'the,table,is,on,the,desk',
'the,table,is,on|the,desk',
'the,table,is|the,desk',
].forEach((x) => {
console.log(`Check: ${x} : ${checkWord('on', x)}`);
});Run Code Online (Sandbox Code Playgroud)
解释:
我在这里为每种可能创建多个捕获组:
(^.*\son$)on 是最后一个词
(^on\s.*)on 是第一个词
(^on$)on 是唯一的词
(^.*\son\s.*$)on 是一个中间词
\s表示空格或换行
const regex = /(^.*\son$)|(^on\s.*)|(^on$)|(^.*\son\s.*$)/i;
console.log(regex.test('phones are good'));
console.log(regex.test('keep it on the table'));
console.log(regex.test('on'));
console.log(regex.test('keep iton the table'));
console.log(regex.test('keep it on'));
console.log(regex.test('on the table'));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25067 次 |
| 最近记录: |