【发布时间】:2015-07-14 19:19:33
【问题描述】:
我想使用以下代码在字符串中查找以特定字母开头的单词。特定字母将由用户在文本框中提供。
这就是我所拥有的:
<!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>
【问题讨论】:
-
使用正则表达式
\bW[^\b\s]+\gi查找以“W”或“w”开头的单词。 -
如何在正则表达式的示例中插入用户提供的单词的第一个字母,即“W”? ,
-
我得到了以下答案及其工作,谢谢 var regx = new RegExp("(\\b"+p+"\\S+\\b)","ig");
标签: javascript regex search word