在链接正则表达式

时间:2018-03-07 14:26:48

标签: javascript regex

是否可以使用正则表达式匹配包含特定文本的链接? 我需要在href值之后添加一些文本。 我尝试在以下链接中匹配“word”:

<a href="http://word/sth">some link</a>

我试过了,但没有成功:

(https?:\/\/[^word"]+)

2 个答案:

答案 0 :(得分:1)

你实际上并不需要^和$ 括号也是匹配给定集合中的单个字符。

尝试:

https?:\/\/(word)

有用的资源:您可以测试正则表达式here

答案 1 :(得分:0)

如果是一个选项,你可以使用DOM而不是正则表达式:

&#13;
&#13;
var div = document.createElement('div');
div.innerHTML = '<a href="http://word/sth">some link</a>';
if (div.firstChild.innerHTML.indexOf("some") !== -1) {
  console.log("contains some!");
  div.firstChild.href += " added text";
}
console.log(div.firstChild);
&#13;
&#13;
&#13;