strstr() [jQuery/Javascript]
By | Wednesday, January 11, 2012


Hide CommentsString: Needle:







jQuery:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function strstr(){
var str $("#str").val(); //STRING HAYSTACK
var needle $("#needle").val(); //NEEDLE
var n = str.indexOf(needle); //POSITION OF FIRST "NEEDLE" IN THE STRING

if(needle){
if(n>=0){
var s = str.split(needle); //SPLITS STRING BY THE "NEEDLE"
var before = s[0]; //SUBSTR BEFORE THE FIRST "NEEDLE"
var after = ''; //(IMPORTANT) NULL VARIABLE UNTIL INSIDE THE "FOR LOOP"

//"FOR LOOP" TO DISPLAY THE 2ND PART OF STRING FROM THE "NEEDLE" ON AFTER
for(i=n; i<str.length; i++){
after += str[i];
}

$("#strstr").html("Before Needle: <b>"+before+"</b> On after: <b>"+after+"</b>"); //DISPLAYS BOTH PARTS IN HTML
}
{
$("#strstr").html("Needle not found in string.");
}
}
{
$("#strstr").html("");
}
}
</script>
</head>
<body>
<input id="str"><input id="needle" onKeyUp="strstr()"><br>
<span id="strstr"></span>
</body>
</html>