我想使用以下代码找到以字符串中的特定字母开头的单词。特定字母将由用户在文本框中提供。
这就是我所拥有的:
<!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>
答案 0 :(得分:2)
您可以使用字词边界\b
,以下示例显示如何匹配以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);
&#13;