Hugh Chalmers Hugh Chalmers - 27 days ago 7
Javascript Question

Check if variable contains certain word in JS

I'm working on a site, you enter a name into a text box, it then saves your input as a variable in Javascript, then it does this.

var url = "http://example.com" + name_input
, so
var url
could be http://example.com/hugh. How would I check if the url variable contains a string such as "apple", or other words?

Answer

There is an in-built function in Javascript which returns the index of the first occurrence of the given string or else -1 if not existed.

var name_input = "hugh";
var url = "http://example.com/" + name_input;
if(url.indexOf("apple") != -1)
    console.log("'apple' existed in "+url);
else
    console.log("'apple' not existed in "+url);

refer http://www.w3schools.com/js/js_string_methods.asp