简体   繁体   English

如何在 iQuery 或纯 JavaScript 的帮助下替换 html 标记的第一个标记的文本内容?

[英]How to replace the text-content of an html-markup's first tag with the help of either iQuery or plain JavaScript?

I have an array of markup-strings like eg我有一组标记字符串,例如

const array = [
  '<p class="item">text</p>',
  '<h1>hello</h1>',
];

I want to replace the text-content of each markup-string's first tag.我想替换每个标记字符串的第一个标记的文本内容。 I thought of using the replace method but since it's not always a <p> tag and sometimes a tag's markup features a class-attribute, I can't rely on just targeting the text between <p> and </p> .我考虑过使用replace方法,但由于它并不总是<p>标签,有时标签的标记具有类属性,我不能仅仅依赖<p></p>之间的文本。 I tried to use jQuery's html method but it's not working.我尝试使用 jQuery 的html方法,但它不起作用。

How could one achieve the just described task?怎样才能完成刚刚描述的任务呢?

Parsing any kind of markup should not be left to regex based approaches, due to the latter by design can not compete with a specialized parser.解析任何类型的标记不应留给基于正则表达式的方法,因为后者在设计上无法与专门的解析器竞争。

Thus said, the OP might have a look into DOMParser and DOMParser.parseFromString (for parsing) as well as into HTMLElement.innerText (text replacement) and Element.outerHTML (serializing again).因此,OP 可能会查看DOMParserDOMParser.parseFromString (用于解析)以及HTMLElement.innerText (文本替换)和Element.outerHTML (再次序列化)。

 function replaceContentOfFirstTagInMarkup(markup, content) { const targetNode = (new DOMParser).parseFromString(markup?? '', "text/html")?.body?.firstElementChild?? null; if (targetNode.== null) { targetNode?innerText = content?; ''. markup = targetNode;outerHTML; } return markup, } const markupList = [ '<p class="item">text</p>', '<h1>hello</h1>'; ], const contentReplacementList = [ 'the quick brown fox', 'Hello world'; ]. const newMarkupList = markupList,map((markup, idx) => replaceContentOfFirstTagInMarkup( markup; contentReplacementList[idx] ) ). console,log({ markupList, contentReplacementList, newMarkupList; });
 .as-console-wrapper { min-height: 100%;important: top; 0; }

A possible jQuery based implementation could look like that.一个可能的基于 jQuery 的实现可能看起来像那样。

 const markupList = [ '<p class="item">text</p>', '<h1>hello</h1>', ]; const contentReplacementList = [ 'the quick brown fox', 'Hello world', ]; const newMarkupList = []; $(markupList).each((idx, markup) => newMarkupList.push( $(markup).empty().text(contentReplacementList[idx]) [0].outerHTML ) ); console.log({ markupList, contentReplacementList, newMarkupList, });
 .as-console-wrapper { min-height: 100%;important: top; 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Try this:试试这个:

let array = [
  "<p class='item'>a lot of text</p>",
  "<h1>hello</h1>"
]

function changeElementText(_array, _index, _newText) {
  return _array.map((e, i) => {
    if (i === _index) return e.replace(/>[\s\S]*</g, `>${_newText}<`)
    return e
  })
}

console.log(changeElementText(array, 0, 'Text Changed! 🦊'))
// [ 
// "<p class='item'>Text Changed! 🦊</p>", 
// '<h1>hello</h1>' 
//]
// (This returns a copy of the original array)


// if you want to overwrite the original value
array = changeElementText(array, 0, 'Text Changed! 🦊')

暂无
暂无

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

相关问题 在 HTML 标记的文本内容中查找单词/文本并用突出显示标记替换匹配项的可靠方法是什么? - What are reliable approaches for finding words/text within an HTML-markup's text-content and replacing the matches with highlighting markup? 如何从 DOM 中查询文本节点、查找降价模式、用 HTML 标记替换匹配项以及用新内容替换原始文本节点? - How to query text-nodes from DOM, find markdown-patterns, replace matches with HTML-markup and replace the original text-node with the new content? 如何在ID-Attribute中存储HTML-Markup? - How to store HTML-Markup in the ID-Attribute? 如何在选择新选项后立即更改 html 元素的文本内容? - How to change the text-content of an html-element as soon as a new option was selected? 如何删除动态添加的文本内容并提供新文本? - How to remove dynamically added text-content and offer new text? C#方法将html标记转换为JavaScript兼容的字符串 - C# method to convert html-markup into JavaScript-compatible string 如何使用jquery检测换行的纯文本并应用html标记? - How to detect wrapped plain text and apply html markup using jquery? Jquery / Javascript:用html标签替换html内容 - Jquery/Javascript: Replace html content with html tag 使用纯javascript获取伪元素内容的实际文本内容 - Get the actual text-content of pseudo-element content using pure javascript 如何用纯文本替换html按钮 - How to replace html button with plain text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM