简体   繁体   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>

I only want the capital letters to be a hyperlink, it seems really easy but i cant find an answer online. 我只希望大写字母是一个超链接,这似乎很容易,但是我无法在线找到答案。 (-.-) (-.-)

Something like this would do it 这样的事情会做到的

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>');
  });
}

EDIT: When you want to only replace a single word you can omit the \\s group in the regex: This regex still matches at minimum two uppercase characters to prevent misdetection of capitalized words or names. 编辑:当您只想替换一个单词时,可以省略正则表达式中的\\ s组:此正则表达式仍至少匹配两个大写字符,以防止误检测大写单词或名称。

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

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

相关问题 仅当在文本字段中键入正确的单词时,才能使链接有效? - How can I make a link work, only when a correct word is typed into a text field? Javascript - 如何从文本中创建链接,不包括任何已创建的链接? - Javascript - how can I make links from text excluding any already made link? 我怎样才能从<input>标记到 javascript - How can I take text from <input> tag to javascript 我可以使用“this”从按钮中获取文本吗? - Can I use 'this' to take text from a button? 我如何从文本框中检测到最后键入的单词 - how can i detect the last typed word from a text box 如何从扩展名为(.rtf)的Word文档中获取文本? - How can i get the text from a word document with (.rtf) extension? 如何从 Word 文件 (.docx) 中获取文本文件? - How can I get text file from Word file (.docx)? 如何通过双击将一个单词作为网页输入? - How can I take a word as a input from a web page by double clicking on it? 如何获取用户的链接以用作按钮链接? - How do i take a link from a user to use as button link? 如何使用 Jquery 使我的文本框仅包含数字和(逗号)以及空格和 + 字符? - How Can I make it possible that my Text box will take only numbers and ,(coma) and spaace and + characters using Jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM