如何在字符串中包装第一个单词而不用 Javascript 包装 HTML 元素?

Gre*_* R. 2 javascript regex

我希望将第一个单词包装在一个字符串中,例如:

var html = '<br> <br> Hello world!';
Run Code Online (Sandbox Code Playgroud)

我有以下代码:

html.replace(/^\s*\w+/, '<div class="underline">$&</div>');
Run Code Online (Sandbox Code Playgroud)

这将输出:

<div class="underline"><br></div> <br> Hello world!
Run Code Online (Sandbox Code Playgroud)

我怎样才能忽略 HTML 标签,以便输出是这样的,第一个单词“Hello”被包裹在 DIV 中?:

<br> <br> <div class="underline">Hello</div> world!
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

您可以使用 DOMParser 从字符串中创建一个文档,然后查看文档中的文本节点以找到修剪后的文本不是空字符串的节点。将该节点替换为<div class="underline">

// https://stackoverflow.com/questions/2579666/getelementsbytagname-equivalent-for-textnodes
const getTextNodes = (parent) => {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    const nodes = [];

    while(node = walker.nextNode()) {
        nodes.push(node);
    }
    return nodes;
};

const html = '<br> <br> Hello world!';
const doc = new DOMParser().parseFromString(html, 'text/html');
const nodes = getTextNodes(doc.body);
const node = nodes.find(node => node.textContent.trim() !== '');
const [, firstWord, rest] = node.textContent.match(/(\S+)(.*)/);
const newNode = document.createElement('div');
newNode.className = 'underline';
newNode.textContent = firstWord;
node.replaceWith(newNode);
newNode.insertAdjacentHTML('afterend', rest);
console.log(doc.body.innerHTML);
Run Code Online (Sandbox Code Playgroud)