如何查找以特定字母开头的单词?

How do I find words starting with a specific letter?

我想使用以下代码在字符串中查找以特定字母开头的单词。具体字母将由用户在文本框中提供。

这是我的:

<!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

开头的每个单词

var string ="hallo, this is a test john doe .Another tea house pole. Hey Tom."
result = string.match(/(\bt\S+\b)/ig);
//result = string.match(/(\st\S+)/ig); // alternative
document.write(result);