简体   繁体   English

根据第一个字母将所有单个单词包装在一个 span 标签中

[英]Wrap all individual words in a span tag based on their first letter

I am trying to wrap each individual word on a webpage in a tag so I can style them individually based on their starting letter.我试图将网页上的每个单词包装在一个标签中,这样我就可以根据它们的首字母分别设置它们的样式。

I have found this method of wrapping each word in a span tag individually, but I can't figure out how to vary the class based on the first letter of the word.我发现了这种将每个单词单独包装在 span 标签中的方法,但我不知道如何根据单词的第一个字母来改变 class。

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, '$1<span class="word">$2</span>');

What you're trying to achieve can't be done with regex if you want to reference the individual words.如果您想引用单个单词,则无法使用正则表达式来完成您想要实现的目标。

I've wrote a little snippet that uses document.querySelector() instead我写了一个使用document.querySelector()的小片段

outerText property on the query selector object returns a plain text string which is later converted to an array with split() function查询选择器上的 outerText 属性 object 返回纯文本字符串,稍后使用split()将其转换为数组 function

Then it simply loops over the array and appends the style tag and to get the first letter I've used substring() function然后它简单地遍历数组并附加样式标签并获取我使用的第一个字母substring() function

 const words = document.querySelector("#words").outerText.split(" "); const wordsDiv = document.querySelector("#words") wordsDiv.innerHTML = "" words.map((el) => { wordsDiv.innerHTML += `<span class="${el.substring(0, 1)}">${el}</span> ` })
 <div id="words">red green blue orange</div>

Try this:尝试这个:

let e = document.getElementById('words');
// Create array with words
let words = e.innerHTML.split(' ');
// Object with CSS classes and corresponding letter
const classes = {
    a: 'class-one',
    b: 'class-two',
    // and so on
}
// Return array with the new strings
words = words.map(word => {
    const firstLetter = word.substring(0,1);
    return `<span class="${classes[firstLetter]}">${word}</span>`;
});
// Join the array and update the DOM
e.innerHTML = words.join(' ');

Here the following is happening:这里发生了以下情况:

  • Words are being separated by a space, creating an array;单词被空格分隔,创建一个数组;
  • The classes constant must receive, as in the example, the correspondence of each letter with its class; classes常量必须像示例中那样接收每个字母与其 class 的对应关系;
  • In the function of the map method, the first letter of the word is being returned and the classes object is accessed with that letter;map方法的 function 中,返回单词的第一个字母,并使用该字母访问类 object;
  • Finally we do a join to join all the texts separating them with a space.最后,我们进行join以连接所有用空格分隔的文本。

Remembering that if there is more than one space between words, inconsistencies will occur, as the first letter will be a space.请记住,如果单词之间有多个空格,则会出现不一致,因为第一个字母将是一个空格。

From the string.prototype.replace reference, you can also add a replace function to the method, instead of an string.string.prototype.replace引用中,您还可以将替换 function添加到方法中,而不是字符串。 The replace function has this form .替换 function 具有这种形式

So, if I didn't misinterpret your problem, you can do something similar to this:所以,如果我没有误解你的问题,你可以做类似的事情:

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, function(match, p1, p2) {
    const myClasses = {
        a: "aword",
        b: "bword",
        ...
    }
    return `${p1}<span class="${myClasses[p2[0]]}">${p2}</span>'
});

You could do something like this:你可以这样做:

  1. Select all the children Select 全体小朋友
  2. map them with their text content map 他们及其文本内容
  3. Split the text into single words将文本拆分为单个单词
  4. map again with some styled html map 再次使用一些样式 html
  5. Join, render and enjoy.加入、渲染和享受。

 words.innerHTML = [...words.children].flatMap(el => el.innerText.replace(/\n/ig, " ").split(" ")).map(el => `<div class="someClass">${el}</div>`).join("")
 .someClass { color: red; background: orange; margin: 10px; }
 <div id="words"> <div> Some dummy content <span>Some other nested dummy content</span> </div> <p>Some sibling content</p> </div>

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

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