将ID分配给html文本

时间:2018-02-12 23:23:28

标签: javascript html

如何使用vanilla javascript为某些单词指定唯一的id标记?例如:

<p>All the king's horses ran away.</p>

单词“All”获取id“term1”,“King's”获得“term2”,“away”获得“term3”等,但句子中的每个单词都将被分配一个身份。

我目前正在使用替换方法,但我认为这是错误的方法:

var str = document.getElementsByTagName('p')[0].innerHTML;

function addId() {
  txt = str.replace(/all/i, '<span id="term1">$&</span>').replace(/king's/i, '<span id="term2">$&</span>').replace(/away/i, '<span id="term3">$&</span>');
  document.getElementsByTagName('p')[0].innerHTML = txt;
}

window.onload = function() {
  addId();
};
<p>All the king's horses ran away.</p>

这迫使我链接一堆替换命令,每次更改id名称。我不认为这是最好的解决方案。什么是最好的方法呢?谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

我相信这应该可以完成工作。您可以使用白名单替换黑名单。这取决于您的使用案例。此外,addIds可以使用Array.map代替Array.forEach,这将使整个功能成为一个单行。这个例子势在必行,因为它更具可读性。

// string - string where we want to add ids
// blackList - words we want to skip (can be whiteliste black list is more general)
function addIds(string, blackList = ['the', 'a']) {
  const stringArray = string.split(' ') // split string into separate words
  let stringWithIds = string // this will be final string

  stringArray.forEach((item, index) => {
    // skip word if black listed
    if (blackList.indexOf(item.toLowerCase()) !== -1) {
      return
    }
    stringWithIds = stringWithIds.replace(item, `<span id="term${index}">${item}</span>`) // add id to word if not black listed
  })

  // replace string with our string with ids
  document.getElementsByTagName('p')[0].innerHTML = stringWithIds;
}

window.onload = function() {
  const str = document.getElementsByTagName('p')[0].innerHTML;
  addIds(str); // you can pass custom blacklist as optional second parameter
};
<p>All the king's horses ran away.</p>

答案 1 :(得分:0)

我认为这个功能对于任务来说足够灵活:

&#13;
&#13;
// Here, your logic to decide if the word must be tagged
const shouldBeTagged = word => {
  return true
}

function addId(str) {
  // Split the string into individual words to deal with each of them
  // one by one
  let txt = str.split(' ').map((word, i) => {
  // Should this word be tagged
  	if (shouldBeTagged(word)) {
      // If so, tag it
  	  return '<span id="term' + i + '">' + word + '</span>'
  	} else {
      // Otherwise, return the naked word
  	  return word
  	}
  // Join the words together again
  }).join(' ')
  document.getElementsByTagName('p')[0].innerHTML = txt;
}

window.onload = function() {
  addId(document.getElementsByTagName('p')[0].innerHTML);
};
&#13;
<p>All the king's horses ran away.</p>
&#13;
&#13;
&#13;