How to find sub-string between the two words using jQuery ?
Given a string containing words and the task is to find substring between two given words using jQuery. There are two methods to solve this problem which are discussed below:
Using match() method: It searches a string for a match against any regular expression and if the match is found then it returns the match string as an array.
Syntax:
string.match( regexp )
Approach:
- Get the string from the HTML element.
- Provide the regular expression in the format like “starting_word(.*)ending_word”.
- The substring between the starting_word and ending_word(exclusivly) will be extracted.
Example:
<!DOCTYPE html> < html > < head > < title > How to find substring between the two words using jQuery ? </ title > < script src = "https://code.jquery.com/jquery-1.12.4.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h2 >Given String</ h2 > < h4 > w3wiki: A computer science portal for Beginner </ h4 > < p > Click on the button to get the< br > substring between "A" and "for" </ p > < button onclick = myBeginner ()> Click Here! </ button > < p id = "GFG" ></ p > < script > function myBeginner() { $(document).ready(function() { $("button").click(function() { var str = "w3wiki: A computer" + " science portal for Beginner"; var subStr = str.match("A(.*)for"); document.getElementById('GFG').innerHTML = subStr[1]; }); }); } </ script > </ body > </ html > |
Output:
Using split() method: It simply split a string into an array of substrings by a specified character or string and returns the new array.
Syntax:
string.split( separator, limit )
Approach:
- Get a string from the HTML element.
- Split the string into substring on the basis of starting_word and ending_word.
- The substring between the starting_word and ending_word(exclusivly) will be extracted.
Example:
<!DOCTYPE html> < html > < head > < title > How to find substring between the two words using jQuery ? </ title > < script src = "https://code.jquery.com/jquery-1.12.4.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h2 >Given String</ h2 > < h4 > w3wiki: A computer science portal for Beginner </ h4 > < p > Click on the button to get the< br > substring between "A" and "for" </ p > < button onclick = myBeginner ()> Click Here! </ button > < p id = "GFG" ></ p > < script > function myBeginner() { $(document).ready(function() { $("button").click(function() { var str = "w3wiki: A computer" + " science portal for Beginner"; var subStr = str.split('A').pop().split('for')[0]; document.getElementById('GFG').innerHTML = subStr; }); }); } </ script > </ body > </ html > |
Output: