aalan

Find a word in a string using JavaScript

To find a word in a string using JavaScript get I will be showing 2 methods to achieve this:

Method 1:

JavaScript String includes() Method

The includes() method determines whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not. Note: The includes() method is case sensitive.

var str = "Hello world, welcome to the ourpcgeek";
var n = str.includes("ourpcgeek");
var str = "Hello world, welcome to the ourpcgeek";
var test= "ourpcgeek";
var n = str.includes(test);

Put the above sample code in console and see the output.

Definition and Usage

The includes() method determines whether a string contains the characters of a specified string.

This method returns true if the string contains the characters, and false if not.

Note: The includes() method is case sensitive.

Click here to see demo

Method 2:

Other method is using RegEx

Following script will find and replace:

var stringToGoIntoTheRegex = "ourpcgeek";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#ourpcgeek#/g;

var input = "Hello this is #ourpcgeek# some #ourpcgeek# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

Following script will find and if there is match then it is show +ve number.

var stringToGoIntoTheRegex = "ourpcgeek";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#ourpcgeek#/g;

var input = "Hello this is #ourpcgeek# some #ourpcgeek# stuff.";
var output = input.search(regex);
alert(output); // Will show positive no. as there is match and the no. will be the location

Following script will find and if there is no match then it is show -ve number.

var stringToGoIntoTheRegex = "xyz";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#ourpcgeek#/g;

var input = "Hello this is #ourpcgeek# some #ourpcgeek# stuff.";
var output = input.search(regex);
alert(output); // Will show -ve number as there is no match

In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some special characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

Leave a comment

You must login to add a new comment.

[wpqa_login]