Search This Blog

Monday, July 4, 2016

How to use contains in javascript?

We cannot directly use contains in javascript. We need to use indexOf() as an alternate to contains in javascript
Example:
var str = "Hello world, welcome to the universe.";
var res = str.indexOf("world");
If the given string is present ,then indexOf() will return index of that string.
So, the above code gives 6 as output(6 is index of string 'world')
other Example:
var str = "Hello world, welcome to the universe.";
var res = str.indexOf("King");
The above code gives -1 as output as 'king' is not present in input string "str".
So,as an alternate to conatins() we need to use indexOf() like this
if(str.indexOf("world") != -1) {
if string matches,it comes into this block
} else {
if string doesn't match,it will come to this block
}

Note: Test the below piece of code by coping it into the following Editor.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to locate the first occurance of the letter .</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
   var str = "Hello world, welcome to the universe.";
var res = str.indexOf("world");
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

No comments:

Post a Comment