JavaScript See If One String Is Contained In Another

String matching in JavaScript is very simple. Suppose that you want to find out if the string "tex" is contained a bigger string, let's say "This is my text"?

Example 1 (ex1.js):


var text = "This is my text";
var pat = "tex";

if ( text.indexOf ( pat ) === -1 ) {
	console.log ( "not found" );
} else {
	console.log ( pat+" is in the string "+text );
}



The function indexOf returns -1 if no match occurs or the position of the first match if one is found.

If you have node.js installed you can run this with:

$ node. ex1.js

If you want to run this in your browser try (ex1.html):

<html>
<head>
<script>

var text = "This is my text";
var pat = "tex";

if ( text.indexOf ( pat ) === -1 ) {
	alert ( "not found" );
} else {
	alert ( pat+" is in the string "+text );
}

</script>
</head>
<body>
Just hello silly world for a body.
</body>
</html>


You should get the output (ex1.out):

tex is in the string This is my text


Some things to note:

  1. indexOf is upper lower case. JavaScript is a case sensitive language. I have typed in indexof a bunch of times.
  2. indexOf returns -1 for not found. You have to include the === -1.
  3. === is better than == because it compares both the value and the type.

If you really want a "contains" function for strings you can create one. I have seen this in a friend's code (ex2.js):


String.prototype.contains = function(s) {
	return this.indexOf(s) !== -1;
};



What if my pattern is a regular expression?

If you need more than a simple text pattern then using s.search(/pattern/) is in order. Suppose that you want to find if there is a number in a string.

Example 3 (ex3.js):



var text = "My address is 123, Golden Carrot Rd.";

if ( text.search ( /[0-9][0-9]*/ ) ) {
	console.log ( "Found a number" );
} else {
	console.log ( "not found" );
}




•       •       •       •       •       •

Summary: # of Words: 269
Author: Philip J. Schlump
Published On: 2013-11-08

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens