繁体   English   中英

如何从文本中提取一个单词并将其链接?

[英]How can I take a word from a text and make it into a link?

<script>
function myClick(){
text = "<b><i>this is my text, THIS NEEDS TO BE A HYPERLINK </i></b>";
document.getElementById('heading1').innerHTML  = document.getElementById('heading1').innerHTML + text;
document.getElementById("heading1").style.textAlign="left";
document.getElementById("heading1").style.marginLeft="5px";

}
</script>

我只希望大写字母是一个超链接,这似乎很容易,但是我无法在线找到答案。 (-.-)

这样的事情会做到的

var text = "<b><i>this is my text, THIS NEEDS TO BE A HYPERLINK </i></b>";
// Regex matching only uppercase letters and whitespaces where there
// have to be at least 2 in a row to match
var match = text.match(/[A-Z\s]{2,}/);
if (match && match.length) {
  match.forEach(function (str) {
    text = text.replace(str, '<a href="http://google.com/q=regex">' + str + '</a>');
  });
}

编辑:当您只想替换一个单词时,可以省略正则表达式中的\\ s组:此正则表达式仍至少匹配两个大写字符,以防止误检测大写单词或名称。

    var match = text.match(/[A-Z]{2,}/);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM