如何找到以特定字母开头的单词? [英] How do I find words starting with a specific letter?
本文介绍了如何找到以特定字母开头的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用以下代码找到以字符串中的特定字母开头的单词。特定字母将由用户在文本框中提供。
I want to find words which start with a specific letter in a string using the following code. The specific letter would be supplied by the user in a text box.
这就是我所拥有的:
<!DOCTYPE html>
<html>
<body>
<input id="srch" type="text" />
<button onClick=searchword()>Search</button>
<p id="wrd" > hallo, this is a test john doe .
Another tea house pole.
</p>
</body>
<script>
function searchword() {
var s = document.getElementById("wrd").innerHTML;
var p= document.getElementById("srch").value;
var regx = new RegExp("(?:^|\W)" + p + "(\w+)(?!\w)","gi");
var re = regx, match, matches = [];
while (match = re.exec(s)) {
matches.push(match[0]);
}
alert(matches);
}
</script>
</html>
推荐答案
您可以使用字边界 \b
,以下示例显示如何匹配以 t开头的每个单词
You can use word boundaries \b
, the following example shows how to match every word starting with t
var string ="hallo, this is a test john doe .Another tea house pole. Hey Tom."
result = string.match(/(\bt\S+\b)/ig);
alert(result);
这篇关于如何找到以特定字母开头的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文