Looking for a string inside another string
If you want to find a string inside another string, there are many options available, each one will depend on the result and performance you are looking for.
by Génesis García Morilla
August 12, 2015
HTML
We should spread and share our knowledge with others to build a better world
<ul>
<li>( /Knowledge/i ).test( str ) = <strong id="test1"></strong></li>
<li>( /gazpacho/i ).test( str ) = <strong id="test2"></strong></li>
</ul>
<ul>
<li>( /Knowledge/i ).exec( str ) = <strong id="exec1"></strong></li>
<li>( /gazpacho/i ).exec( str ) = <strong id="exec2"></strong></li>
</ul>
<ul>
<li>str.match( /OU/gi ) = <strong id="match1"></strong></li>
<li>str.match( /OU/i ) = <strong id="match2"></strong></li>
<li>str.match( /gazpacho/i ) = <strong id="match3"></strong></li>
</ul>
<ul>
<li>str.search( /Knowledge/i ) = <strong id="search1"></strong></li>
<li>str.search( /gazpacho/i ) = <strong id="search2"></strong></li>
</ul>
<ul>
<li>str.indexOf( /Knowledge/i ) = <strong id="indexOf1"></strong></li>
<li>str.indexOf( "knowledge" ) = <strong id="indexOf2"></strong></li>
<li>str.indexOf( "gazpacho" ) = <strong id="indexOf3"></strong></li>
</ul>
We have used insensitive (i) and global (g) case with regular expresion: /OU/gi
CSS
body {
color: #333;
family: arial;
}
li {
list-style-type: none;
}
JavaScript
var str = "We should spread and share our knowledge with others to build a better world";
document.getElementById("test1").innerHTML = (/Knowledge/i).test(str);
document.getElementById("test2").innerHTML = (/gazpacho/i).test(str);
document.getElementById("exec1").innerHTML = (/Knowledge/i).exec(str);
document.getElementById("exec2").innerHTML = (/gazpacho/i).exec(str);
document.getElementById("match1").innerHTML = str.match(/OU/gi);
document.getElementById("match2").innerHTML = str.match(/OU/i);
document.getElementById("match3").innerHTML = str.match(/gazpacho/i);
document.getElementById("search1").innerHTML = str.search(/Knowledge/i);
document.getElementById("search2").innerHTML = str.search(/gazpacho/i);
document.getElementById("indexOf1").innerHTML = str.indexOf(/Knowledge/i);
document.getElementById("indexOf2").innerHTML = str.indexOf("knowledge");
document.getElementById("indexOf3").innerHTML = str.indexOf("gazpacho");