JavaScript Basics: String Contains Function

Sep 18, 2015  • Javascript

In many of the server-side programming languages like C#, the String object has a Contains method that returns a boolean indicating if the string contains another specified string. JavaScript however does not have a .contains method. Fortunately, the .indexOf method in JavaScript can easily be used to mimic or build your own .contains method.

Simple JavaScript String Contains Method

Here’s a simple implementation of a “.contains” function that is case sensitive:

function contains(value, searchFor)
{
	return (value || '').indexOf(searchFor) > -1;
}

Sample Usage:

// returns true
var v1 = contains('one value', 'value');

// returns false
var v2 = contains('another value', 'two');

Something to note about the above method is that it implements a JavaScript Null Coallesce to prevent the method from throwing an exception if null or undefined are passed in. This may or may not be necessary for your use, but most times a false result is preferred over a JavaScript exception.

Master Cloud, AI and DevOps Skills Today! Join the Build5Nines Membership!

Make it Ignore Case

To make it ignore case you just need to modify the function to convert the passed in strings to be either all uppercase or all lowercase. Here’s a modified version that does this:

function contains(value, searchFor)
{
	var v = (value || '').toLowerCase();
	var v2 = searchFor;
	if (v2) {
		v2 = v2.toLowerCase();
	}
	return v.indexOf(v2) > -1;
}

Happy coding!