How to check if text exists in javascript var

I have a var that contains some text. I would like to check if the text has a specific word.

Example:

var myString = 'This is some random text';

I would like to check if the word "random" exists. Thanks for any help.

+3
source share
3 answers

If you want to test the word "random" specifically, you can use a regular expression like this:

Example: http://jsfiddle.net/JMjpY/

var myString = 'This is some random text';
var word = 'random';
var regex = new RegExp( '\\b' + word + '\\b' );

var result = regex.test( myString );

Thus, it will not match where "random" is part of a word of type "randomize".


And, of course, prototype it on String, if you want:

Example: http://jsfiddle.net/JMjpY/1/

String.prototype.containsWord = function( word ) {
    var regex = new RegExp( '\\b' + word + '\\b' );
    return regex.test( this );
};

myString.containsWord( "random" );
+6
source

:

function contains(str, text) {
   return str.indexOf(text) >= 0);
}

if(contains(myString, 'random')) {
   //myString contains "random"
}

:

String.prototype.contains = String.prototype.contains || function(str) {
   return this.indexOf(str) >= 0;
}

if(myString.contains('random')) {
   //myString contains "random"
}
+5

As for Jacob, the function “contains” has a missing opening bracket.

return str.indexOf(text) >= 0);

it should be

return (str.indexOf(text) >= 0);

I selected Patricks answer and adapted it to function

Example

function InString(myString,word)
    {
    var regex = new RegExp( '\\b' + word + '\\b' );
    var result = regex.test( myString );
    return( result );
    }

Call a function with

var ManyWords='This is a list of words';
var OneWord='word';
if (InString(ManyWords,OneWord)){alert(OneWord+' Already exists!');return;}

This will return False, because although words exist in the ManyWords variable, this function only shows the exact match for the word.

+2
source

Source: https://habr.com/ru/post/1787506/


All Articles