简体   繁体   中英

Check if a string contains a specific word only once

I am trying to check if a string contains a specific word only once.

Here is my attempt, but it's not working:

 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);

Here's an approach using filter

 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"));

Use 'regex match' to get the occurrence of a substring in a string.

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.

I have used 'g' for Global checking and 'i' for ignoring the case.

If you want to create 'Regex' object create like this:

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 would just use a regular expression and use the match method on the string you would like to search using the "i" and "g" flag. Below is an example function although there are most likely better ways.

function containsWordOnce(string, word) {
    const re = new RegExp(word, 'ig');
    const matches = string.match(re);
    return matches.length === 1;
}

Just plug in your string and word your trying to find.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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