检查text是否在字符串中

Check if text is in a string

本文关键字:字符串 是否 text 检查      更新时间:2023-09-26

我想检查一些文本是否在字符串中例如,我有一个字符串

str = "car, bycicle, bus"

还有另一个字符串

str2 = "car"

我想检查str2是否在str中

我是一个javascript新手,所以请原谅我:)

if(str.indexOf(str2) >= 0) {
   ...
}

或者如果你想用正则表达式:

if(new RegExp(str2).test(str)) {
  ...
}

但是,在后一种方法中可能会遇到转义(元字符)的问题,因此第一种方法更容易。

ES5

if(str.indexOf(str2) >= 0) {
   ...
}

ES6

if (str.includes(str2)) {
}

str.lastIndexOf(str2) >= 0;这应该可以工作。未经测试。

let str = "car, bycicle, bus";
let str2 = "car";
console.log(str.lastIndexOf(str2) >= 0);

使用内置的.includes() string方法检查子字符串是否存在。
它返回布尔值,指示是否包含子字符串。

const string = "hello world";
const subString = "world";
console.log(string.includes(subString));
if(string.includes(subString)){
   // SOME CODE
}

请使用:

var s = "foo";
alert(s.indexOf("oo") > -1);

你可以这样做:

'a nice string'.includes('nice')

此函数将告诉您子字符串是否在字符串中以及出现了多少次。

 const textInString = (wordToFind, wholeText) => {
    const text = new RegExp(wordToFind, 'g');
    const occurence = wholeText.match(text) ?? [];
    return [occurence.length > 0, occurence.length]
 }
 
 console.log(textInString("is", "This cow jumped over this moon"))

如果你只想检查字符串中的子字符串,你可以使用indexOf,但如果你想检查单词是否在字符串中,其他答案可能无法正常工作,例如:

str = "carpet, bycicle, bus"
str2 = "car"
What you want car word is found not car in carpet
if(str.indexOf(str2) >= 0) {
  // Still true here
}
// OR 
if(new RegExp(str2).test(str)) {
  // Still true here 
}

所以你可以稍微改进一下正则表达式使它工作

str = "carpet, bycicle, bus"
str1 = "car, bycicle, bus"
stringCheck = "car"
// This will false
if(new RegExp(`'b${stringCheck}'b`).test(str)) {
  
}
// This will true
if(new RegExp(`'b${stringCheck}'b`,"g").test(str1)) {
  
}