【问题标题】:How do I find words starting with a specific letter?如何查找以特定字母开头的单词?
【发布时间】: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>

【问题讨论】:

标签: javascript regex search word


【解决方案1】:

你可以使用单词边界\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);

【讨论】:

  • 如何在正则表达式的示例中插入用户提供的单词的第一个字母,即“t”? ,
  • 我得到了以下答案及其工作,谢谢 var regx = new RegExp("(\\b"+p+"\\S+\\b)","ig");
  • 在字母“t”之前有特殊字符时不起作用。例如,它将匹配“étonnant”之类的作品。
  • @Liam 你也可以试试:result = string.match(/(\st\S+)/ig); 避免像tonnant这样的错误匹配
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
相关资源
最近更新 更多