将单词转换为链接并将其替换为html

时间:2019-05-07 19:59:26

标签: javascript jquery string loops dynamic

我有一个包含名称的字符串,该名称可以是动态的(1个或更多).....我想将这些名称转换为超链接...并且那些超链接将包含那些名称..

例如在字符串“ john,jim,jean”中..... john将被超链接并重定向到“ www.abc.com/john”,依此类推……

我已经通过使用......通过jquery访问了元素,因为我使用了.children().text()拆分中的元素并将其保存在regs[]

<label>Ids: <span> john,jim,jean</span></label>
var strr=$('label:contains("IDs:")').children().text();

var regs = strr.split(",") 
var reg_length = regs.length;

我不想更改html中的文本,只想将它们转换为超链接。

就像在单击john时一样,将重定向到www.abc.com/john,以此类推。

不更改可见字符串john,jim,jean

4 个答案:

答案 0 :(得分:6)

我看到您使用了jQuery,所以我也会

regs = regs.map( s => $(`<a href='www.abc.com/${s}'>${s}</a>`) )

map和jquery的帮助下,使用string templates从数组的每个项目创建元素。

答案 1 :(得分:3)

我希望这就是您要寻找的

let spanDom = $("label").find("span");
let str = $(spanDom).text().trim();

let s = str.split(",");

$(spanDom).empty();

s.forEach(function( name ) {
  $(spanDom).append("<a href='www.abc.com/"+name+"'>"+name+"</a>,");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Ids: <span> john,jim,jean</span></label>

答案 2 :(得分:1)

尝试

let w = ["john", "jim", "jean" ];  // list of known words to link

data.innerHTML = data.innerHTML.replace(/\w+/g, 
  x=> w.includes(x) ? `<a href="www.abc.com/${x}">${x}</a>` : x)
<label id='data'>Ids: <span> john,jim,jean</span></label>

答案 3 :(得分:0)

这是完全可以实现的,只要您的字符串遵循常见的分隔模式(例如逗号(,)或空格)即可。我假设您在字符串中的名称用逗号和空格", "隔开,我将在不使用jQuery的情况下显示它。 首先,包含字符串的<span>元素需要具有ID。另外,我正在添加<p>作为超链接的占位符。

<span id="names">John, Jim, Jean </span>
<p id="hps"></p>

现在使用JavaScript:

nameString = document.getElementById("names").innerHTML; //get the string from <span>

nameArray = nameString.split(", "); 
//This method will take the string and break it down wherever it finds the occurrence of the argument (here ", ") and remove these characters and the individual broken down strings are returned as an array 
//nameArray has all the names stored in an array
//Let's create an array links that will hold all your <a> elements
links = new Array();
len = nameArray.length; //Get the length of the array i.e. number of names
for (i = 0; i < len; i++) {
   links[i] = document.createElement("a"); //create an <a> tag
   links[i].setAttribute("href", "www.abc.com/"+nameArray[i]); //Set its href
   links[i].innerHTML = nameArray[i]; //Add Link names i.e. contents inside <a></a>
   document.getElementById("hps").appendChild(links[i]); //append these links as childs to the <p> parent tag
}