如何用jQuery查找两个词之间的子串
给定一个包含单词的字符串,任务是使用jQuery找到两个给定单词之间的子串。有两种方法来解决这个问题,下面将讨论。
使用match()方法:它搜索一个字符串与任何正则表达式的匹配,如果找到了匹配,那么它将匹配的字符串作为一个数组返回。
语法:
string.match( regexp )
步骤:
- 从HTML元素中获取字符串。
- 提供格式为 “starting_word(.*)ending_word “的正则表达式。
- 在start_word和ending_word之间的子串将被提取(exclusive)。
示例:
<!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;" >
GeeksforGeeks
</h1>
<h2>Given String</h2>
<h4>
GeeksforGeeks: A computer
science portal for geeks
</h4>
<p>
Click on the button to get the<br>
substring between "A" and "for"
</p>
<button onclick=myGeeks()>
Click Here!
</button>
<p id="GFG"></p>
<script>
function myGeeks() {
(document).ready(function() {
("button").click(function() {
var str = "GeeksforGeeks: A computer"
+ " science portal for geeks";
var subStr = str.match("A(.*)for");
document.getElementById('GFG').innerHTML
= subStr[1];
});
});
}
</script>
</body>
</html>
输出:
*在点击按钮之前。
* 点击按钮后。
使用split()方法:它简单地将一个字符串按指定的字符或字符串分割成一个子串数组,并返回新的数组。
语法:
string.split( separator, limit )
步骤:
- 从HTML元素中获取一个字符串。
- 在start_word和ending_word的基础上将字符串分割成子串。
- 在start_word和ending_word之间的子串将被提取(exclusive)。
示例:
<!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;" >
GeeksforGeeks
</h1>
<h2>Given String</h2>
<h4>
GeeksforGeeks: A computer
science portal for geeks
</h4>
<p>
Click on the button to get the<br>
substring between "A" and "for"
</p>
<button onclick=myGeeks()>
Click Here!
</button>
<p id="GFG"></p>
<script>
function myGeeks() {
(document).ready(function() {
("button").click(function() {
var str = "GeeksforGeeks: A computer"
+ " science portal for geeks";
var subStr =
str.split('A').pop().split('for')[0];
document.getElementById('GFG').innerHTML
= subStr;
});
});
}
</script>
</body>
</html>
输出:
*在点击按钮之前。
* 点击按钮后。