lafish.blogg.se

Javascript string contains substring
Javascript string contains substring













  • Finally, call this method with two different words as sub-string to the above main string.
  • In this example, our main string is “Hello World”.
  • Print out the message to the user accordingly. If it is greater than or equal to 0, means that the substring exists inside the given string.
  • Inside the function, check the value of indexOf method.
  • Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to. It prints out the result based on subString exists in mainString or not. () The indexOf () method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. subString is the sub-string and mainString is the main string.
  • doesExist method takes two parameters.
  • The commented numbers in the above program denote the step number below : Let output = document.querySelector("h1") ītnCheck.//1 function doesExist ( subString, mainString ) //3 var mainString = "Hello World" //4 doesExist ( "Hello", mainString ) doesExist ( "Universe", mainString ) Explanation : Let btnCheck = document.querySelector("button")

    javascript string contains substring

  • We are displaying the result in the h1 element using the innerText property.
  • javascript string contains substring

    Depending upon the result of the check, we will assign “Yes” or “No” to the result variable.For ECMAScript 5 or older environments, should be used instead, which returns -1 when a substring cannot be found. If it returns true, that means myString does contain str substring. ECMAScript 6 introduced, which is case-sensitive and not supported by Internet Explorer without a polyfill. Further, we are using the includes() method to verify whether myString contains str substring or not.We are converting both the strings into lowercase by calling toLowerCase() method so that we can ignore the case and and perform case-insensitive check.In the event handler function, we have str variable that hold a substring as its value.We have a global variable myString which holds a string as its value.We have attached a click event listener to the button element.We have selected the button element and h1 element using the document.querySelector() method and stored them in btnCheck and output variables respectively.















    Javascript string contains substring