本文介绍了如何查找以特定字母开头的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

推荐答案

可以使用词边界,下面的例子展示了如何匹配每个以t

You can use word boundaries , 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(/(tS+)/ig);
//result = string.match(/(stS+)/ig); // alternative
document.write(result);

这篇关于如何查找以特定字母开头的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 20:27