InterviewSolution
| 1. |
Regular Expression in JavaScript to display digits from a string with numbers |
|
Answer» <P>To search for a string in a string, use the search() method. The method searches a string for a specified value. The returned value is the position of the match. However, -1 is returned if the match isn’t found. LET’s say we have the following string: var myStr = "Popular Programming LANGUAGES";We want to search the below string from the above string: LanguagesFor that, use the search() method: var RES = myStr.search("Languages");Let us see the example wherein the string is successfully searched and the result (position) is displayed on button click: <!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="SHOW()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "Popular Programming Languages" var res = myStr.search("Languages"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>The output displays the position: Let us now see another example, wherein -1 is returned since the string to be found isn’t there: <!DOCTYPE html> <html> <body> <p>Click the below button...</p> <button onclick="show()">Search</button> <p id="myid"></p> <script> function show() { var myStr = "This is an example!" var res = myStr.search("demo"); document.getElementById("myid").innerHTML = res; } </script> </body> </html>The output on button click displays -1: |
|