Hugh Chalmers Hugh Chalmers - 9 months ago 49
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 = "" + name_input
, so
var url
could be How would I check if the url variable contains a string such as "apple", or other words?

Answer Source

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 = "" + name_input;
if(url.indexOf("apple") != -1)
    console.log("'apple' existed in "+url);
    console.log("'apple' not existed in "+url);