gpt4 book ai didi

javascript - 不可知的方式来匹配和包装 body 中的所有字符串(无需知道 html 结构)

转载 作者:可可西里 更新时间:2023-11-01 15:01:38 25 4
gpt4 key购买 nike

我有一个文件 strings.json 其中包含

{
"fname": "First Name",
"lname": "Last Name",
"email": "Email"
}

我有另一个文件 index.html 其中包含

  First name <input type="text" name="fname">
Last name
Email

如果 html 文件包含 json 文件中存在的字符串,我想使用 span 和数据属性将其包装起来,使用 Javascript 或 JQuery,例如:

 <span data-string="fname">First name</span><input type="text" name="fname">
<span data-string="lname">Last name</span>
<span data-string="email">Email</span>

我不想要这样的解决方案question ,我的问题很相似,但主要区别在于我想要一个不可知的代码,它可以在不知道 html 结构的情况下工作,而且我也不想要特定于一种结构的正则表达式。

你只需在 body 中给它字符串,它将所有结果包装在一个如上所示的范围内,仅此而已。我还没有找到不可知论的方法。另一个例子是这个 question ,也不是不可知论者,你必须知道它的 html 结构才能工作。

Markjs 不工作有两个原因:

  • 我想用它来选择字符串,它会突出显示它们,但我不知道如何关闭突出显示
  • 更重要的是:

    var myString = $("body").mark("Hi");
    console.log(myString);
    // returns

    translate.html:17 r.fn.init(1)0: bodyaLink: ""accessKey: ""assignedSlot: nullattributes: NamedNodeMap {length: 0}background: ""baseURI: "file:///home/elie/Desktop/csc/translate.html"bgColor: ""childElementCount: 7childNodes: (14) [text, h1, br, text, mark, text, script, text, script, text, script, text, script, text]children: (7) [h1, br, mark, script, script, script, script]classList: [value: ""]className: ""clientHeight: 88clientLeft: 0clientTop: 0clientWidth: 1264contentEditable: "inherit"dataset: DOMStringMap {}dir: ""draggable: falsefirstChild: textfirstElementChild: h1hidden: falseid: ""innerHTML: "↵ <h1><mark data-markjs="true">Hi</mark>,</h1><br>↵ T<mark data-markjs="true">hi</mark>s is the text that will be translated↵↵↵<script src="jquery-3.2.1.min.js"></script>↵<script src="jquery.mark.min.js"></script>↵<script src="jquery.localize.min.js"></script>↵↵<script type="text/javascript">↵var myString = $("body").mark("Hi");↵console.log(myString);↵</script>↵↵"innerText: "Hi,↵↵↵This is the text that will be translated"isConnected: trueisContentEditable: falselang: ""lastChild: textlastElementChild: scriptlink: ""localName: "body"namespaceURI: "http://www.w3.org/1999/xhtml"nextElementSibling: nullnextSibling: nullnodeName: "BODY"nodeType: 1nodeValue: nullnonce: ""offsetHeight: 88offsetLeft: 0offsetParent: nulloffsetTop: 0offsetWidth: 1264onabort: nullonauxclick: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonbeforeunload: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nullongotpointercapture: nullonhashchange: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonlanguagechange: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonlostpointercapture: nullonmessage: nullonmessageerror: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonoffline: nullononline: nullonpagehide: nullonpageshow: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonpointercancel: nullonpointerdown: nullonpointerenter: nullonpointerleave: nullonpointermove: nullonpointerout: nullonpointerover: nullonpointerup: nullonpopstate: nullonprogress: nullonratechange: nullonrejectionhandled: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonstalled: nullonstorage: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonunhandledrejection: nullonunload: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<body>↵ <h1><mark data-markjs="true">Hi</mark>,</h1><br>↵ T<mark data-markjs="true">hi</mark>s is the text that will be translated↵↵↵<script src="jquery-3.2.1.min.js"></script>↵<script src="jquery.mark.min.js"></script>↵<script src="jquery.localize.min.js"></script>↵↵<script type="text/javascript">↵var myString = $("body").mark("Hi");↵console.log(myString);↵</script>↵↵</body>"outerText: "Hi,↵↵↵This is the text that will be translated"ownerDocument: documentparentElement: htmlparentNode: htmlprefix: nullpreviousElementSibling: headpreviousSibling: textscrollHeight: 88scrollLeft: 0scrollTop: 0scrollWidth: 1264shadowRoot: nullslot: ""spellcheck: truestyle: CSSStyleDeclaration {alignContent: "", alignItems: "", alignSelf: "", alignmentBaseline: "", all: "", …}tabIndex: -1tagName: "BODY"text: ""textContent: "↵ Hi,↵ This is the text that will be translated↵↵↵↵↵↵↵↵var myString = $("body").mark("Hi");↵console.log(myString);↵↵↵"title: ""translate: truevLink: ""__proto__: HTMLBodyElementlength: 1prevObject: [document]__proto__: Object(0)

我希望 console.log 返回 Hi

最佳答案

Dave Gilem 的替换器是一个好的开始,但您需要递归遍历 DOM 并将其仅应用于文本节点。此解决方案依赖于 jQuery。虽然使用 jQuery.each() 遍历 DOM 的速度要慢得多,但这是迄今为止创建新 HTML 节点来代替匹配字符串的最简单方法。

/**
* replace text with <span> according to the wrapList
* @param {Object} $elem jQuery DOM Object of a text node
*/
function replaceText($elem) {
var pattern,
textcontent = $elem.text(),
wrapList = {
"fname": "First name",
"lname": "Last name",
"email": "Email"
};

for (const key in wrapList) {
if (wrapList.hasOwnProperty(key)) {
pattern = new RegExp(wrapList[key], 'g');
// as we do a DOM manipulation, we only want to do it if necessary
if (pattern.test(textcontent)) {
// replace the text node with new text. $& in JS equals $0 in other languages
textcontent = textcontent.replace(pattern,'<span data-string="'+key+'">$&</span>');
}
}
}
// a change has been made
if (textcontent != $elem.text()) {
$elem.replaceWith(textcontent);
}
}

/**
* loop through DOM nodes recursively and call replaceText() on text nodes
* @param {Object} $elem jQuery DOM Object
*/
function replaceRecursive($elem) {
// get the nodeType of the object's DOM node
var nt = $elem.get(0).nodeType;
if (nt === 3) {
// type 3 is a text node: replace the text
replaceText($elem);
} else if(nt === 1) {
// type 1 is a DOM element: loop through the child objects recursively
$elem.contents().each(function () {
replaceRecursive($(this));
});
}
}

// start with the <body> tag
replaceRecursive($('body'));

jsfiddle

编辑:有一个错误:在 for 循环中使用 replaceWith() 总是会更新内容。如果节点中多次出现搜索词,它只会替换最后一个。

关于javascript - 不可知的方式来匹配和包装 body 中的所有字符串(无需知道 html 结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com