Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if text is in a string

Tags:

javascript

I want to check is some text is in a string for instance i have a string

str = "car, bycicle, bus"

and I have another string

str2 = "car"

I want to check if str2 is in str.

I am a newbie in javascript so please bear with me :)

Regards

like image 271
user710502 Avatar asked Jul 07 '11 17:07

user710502


People also ask

How do I check if a text is in string?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you check if a text is in a string in Python?

The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.

How do you check if a char is in a string Python?

Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '

How do you check if a string contains a character?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.


3 Answers

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

Or if you want to go the regex route:

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

However you may face issues with escaping (metacharacters) in the latter, so the first route is easier.

like image 170
Vivin Paliath Avatar answered Sep 21 '22 23:09

Vivin Paliath


ES5

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

ES6

if (str.includes(str2)) {  } 
like image 43
Furkan Durmaz Avatar answered Sep 22 '22 23:09

Furkan Durmaz


str.lastIndexOf(str2) >= 0; this should work. untested though.

let str = "car, bycicle, bus";
let str2 = "car";
console.log(str.lastIndexOf(str2) >= 0);
like image 33
Doug Chamberlain Avatar answered Sep 19 '22 23:09

Doug Chamberlain