如何编写将修剪带有嵌套标签的 HTML 文本的正则表达式



试图找到一个可以转换的正则表达式:

"    <p>   Some text <span> with another text   </span>    </p>  "

到:

"<p>Some text <span> with another text</span></p>"

问题是我找不到从右侧和左侧对标签进行分组的解决方案。

到目前为止,我创建的是:

/((?:^(?:s|(?:<[/]*[w]+>))+)|(?:s|(?:<[/]*[w]+>))+$)/

这可能是一种解决方法,但它将是两步解决方案(所以首先:找到左侧和右侧,其次删除标签外的空格(。

寻找更优雅的东西,这将通过使用正则表达式的一次替换来解决我的问题。提前感谢!

这个解决方案不是正则表达式,但它有效:

function trimElement(root, recursive=false){
  let todo = [root];
  while(todo.length){
    let elm = todo.pop();
    if(recursive) 
      todo.push(...elm.children);
    if(elm.nodeName.toLowerCase() === "script") continue;
    const {firstChild, lastChild} = elm;
    if(firstChild.nodeType === 3)
      firstChild.data = firstChild.data.trimLeft();
    if(lastChild.nodeType === 3)
      lastChild.data = lastChild.data.trimRight();
  }
  
  console.log(root.outerHTML);
}
trimElement(document.querySelector("div"), true);
<div>
    <p>   Some text <span> with another text   </span>    </p>  
</div>

最新更新