Javascript 使用JS查找并替换文档中的特定文本字符

Javascript 使用JS查找并替换文档中的特定文本字符,javascript,jquery,xss,Javascript,Jquery,Xss,我想知道是否有一种轻量级的方法可以使用JavaScript或jQuery在文档中嗅出特定的文本字符;说出€并找到此角色的所有实例

我想知道是否有一种轻量级的方法可以使用JavaScript或jQuery在文档中嗅出特定的文本字符;说出并找到此角色的所有实例<然后编写一个功能,用$替换所有实例

我为初学者找到了以下代码片段:

var str = 'test: &#39;';

str = str.replace(/&#39;/g, "'");

本质上;我想要一个单页文档的解决方案。抓取X的所有实例并使其成为XY。只有文本字符

在javascript中不使用jquery:

document.body.innerText = document.body.innerText.replace('actualword', 'replacementword');
您可以使用:

str.replace(/text/g, "replaced text");

$
替换
@
怎么样

$("body").children().each(function () {
    $(this).html( $(this).html().replace(/@/g,"$") );
});


对于文档
正文
中的每个元素,这会将
replacetext
的所有实例替换为
actualtext

,并使用功能修改它们的文本

$("body *").text(function() {
    return $(this).text().replace("x", "xy");
});

最好是在服务器端执行此操作,或者在将其返回到浏览器之前将货币符号包装到可以选择的元素中,但是如果两者都不是选项,则可以选择正文中的所有文本节点并对其进行替换。下面我使用一个插件来做这件事,这个插件是我2年前写的,用来突出显示文本。我要做的是找到所有出现的欧元,并用类别货币符号将其包装在一个跨度中,然后替换这些跨度的文本

(function($){

    $.fn.highlightText = function () {
        // handler first parameter
        // is the first parameter a regexp?
        var re,
            hClass,
            reStr,
            argType = $.type(arguments[0]),
            defaultTagName = $.fn.highlightText.defaultTagName;

        if ( argType === "regexp" ) {
            // first argument is a regular expression
            re = arguments[0];
        }       
        // is the first parameter an array?
        else if ( argType === "array" ) {
            // first argument is an array, generate
            // regular expression string for later use
            reStr = arguments[0].join("|");
        }       
        // is the first parameter a string?
        else if ( argType === "string" ) {
            // store string in regular expression string
            // for later use
            reStr = arguments[0];
        }       
        // else, return out and do nothing because this
        // argument is required.
        else {
            return;
        }

        // the second parameter is optional, however,
        // it must be a string or boolean value. If it is 
        // a string, it will be used as the highlight class.
        // If it is a boolean value and equal to true, it 
        // will be used as the third parameter and the highlight
        // class will default to "highlight". If it is undefined,
        // the highlight class will default to "highlight" and 
        // the third parameter will default to false, allowing
        // the plugin to match partial matches.
        // ** The exception is if the first parameter is a regular
        // expression, the third parameter will be ignored.
        argType = $.type(arguments[1]);
        if ( argType === "string" ) {
            hClass = arguments[1];
        }
        else if ( argType === "boolean" ) {
            hClass = "highlight";
            if ( reStr ) {
                reStr = "\\b" + reStr + "\\b";
            }
        }
        else {
            hClass = "highlight";
        }

        if ( arguments[2] && reStr ) {
            reStr = reStr = "\\b" + reStr + "\\b";
        } 

        // if re is not defined ( which means either an array or
        // string was passed as the first parameter ) create the
        // regular expression.
        if (!re) {
            re = new RegExp( "(" + reStr + ")", "ig" );
        }

        // iterate through each matched element
        return this.each( function() {
            // select all contents of this element
            $( this ).find( "*" ).andSelf().contents()

            // filter to only text nodes that aren't already highlighted
            .filter( function () {
                return this.nodeType === 3 && $( this ).closest( "." + hClass ).length === 0;
            })

            // loop through each text node
            .each( function () {
                var output;
                output = this.nodeValue
                    .replace( re, "<" + defaultTagName + " class='" + hClass + "'>$1</" + defaultTagName +">" );
                if ( output !== this.nodeValue ) {
                    $( this ).wrap( "<p></p>" ).parent()
                        .html( output ).contents().unwrap();
                }
            });
        });
    };

    $.fn.highlightText.defaultTagName = "span";

})( jQuery );

$("body").highlightText("€","currency-symbol");
$("span.currency-symbol").text("$");
(函数($){
$.fn.highlightText=函数(){
//处理程序第一个参数
//第一个参数是regexp吗?
var re,
hClass,
休息室,
argType=$.type(参数[0]),
defaultTagName=$.fn.highlightText.defaultTagName;
如果(argType==“regexp”){
//第一个参数是正则表达式
re=参数[0];
}       
//第一个参数是数组吗?
else if(argType==“数组”){
//第一个参数是数组,generate
//供以后使用的正则表达式字符串
rest=参数[0]。连接(“|”);
}       
//第一个参数是字符串吗?
else if(argType==“string”){
//将字符串存储在正则表达式字符串中
//供日后使用
rest=参数[0];
}       
//否则,返回,什么也不做,因为
//参数是必需的。
否则{
返回;
}
//但是,第二个参数是可选的,
//它必须是字符串或布尔值。如果是
//字符串,它将用作突出显示类。
//如果它是布尔值且等于true,则
//将用作第三个参数和高亮显示
//类将默认为“突出显示”。如果未定义,
//highlight类将默认为“highlight”,并且
//第三个参数将默认为false,允许
//要匹配部分匹配项的插件。
//**例外情况是,如果第一个参数是常规参数
//表达式,第三个参数将被忽略。
argType=$.type(参数[1]);
如果(argType==“字符串”){
hClass=参数[1];
}
else if(argType==“boolean”){
hClass=“突出显示”;
如果(rest){
rest=“\\b”+rest+“\\b”;
}
}
否则{
hClass=“突出显示”;
}
if(参数[2]&&rest){
rest=rest=“\\b”+rest+“\\b”;
} 
//如果未定义re(表示数组或
//字符串作为第一个参数传递)创建
//正则表达式。
如果(!re){
re=新的RegExp(“(“+rest+”),“ig”);
}
//遍历每个匹配的元素
返回此值。每个(函数(){
//选择此元素的所有内容
$(this.find(“*”)和self().contents()
//仅筛选到尚未高亮显示的文本节点
.filter(函数(){
返回this.nodeType==3&&$(this).closest(“.”+hClass).length==0;
})
//循环遍历每个文本节点
.每个(功能){
var输出;
输出=this.nodeValue
.替换(关于“$1”);
if(输出!==this.nodeValue){
$(this.wrap(“

”).parent() .html(输出).contents().unwrap(); } }); }); }; $.fn.highlightText.defaultTagName=“span”; })(jQuery); $(“正文”)。高亮文本(“€”和“货币符号”); $(“span.货币符号”)。文本($”;
我个人的建议如下:

function nativeSelector() {
    var elements = document.querySelectorAll("body, body *");
    var results = [];
    var child;
    for(var i = 0; i < elements.length; i++) {
        child = elements[i].childNodes[0];
        if(elements[i].hasChildNodes() && child.nodeType == 3) {
            results.push(child);
        }
    }
    return results;
}

var textnodes = nativeSelector(),
    _nv;
for (var i = 0, len = textnodes.length; i<len; i++){
    _nv = textnodes[i].nodeValue;
    textnodes[i].nodeValue = _nv.replace(/£/g,'€');
}
函数nativeSelector(){
var elements=document.queryselectoral(“body,body*”);
var结果=[];
var-child;
对于(var i=0;i对于(var i=0,len=textnodes.length;i使用拆分和联接方法

$("#idBut").click(function() {
    $("body").children().each(function() {
        $(this).html($(this).html().split('@').join("$"));
    });
});

下面是

由于您将使用jQuery,请尝试:

那就做吧

$("p").replaceText("£", "$")
它似乎只在替换文本方面做得很好,而没有与其他元素混淆

ECMAScript 2015+方法 解决此任务时的陷阱 这似乎是一项简单的任务,但您必须注意以下几件事:

  • 简单地替换整个HTML会杀死所有DOM功能,如事件侦听器
  • 替换HTML也可能会替换
    内容,或HTML标记或属性,这并不总是需要的
  • 更改HTML可能导致攻击
  • 您可能需要替换属性,如
    title$("p").replaceText("£", "$")
    
    const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {
      // Handle `string` — see the last section
      [
        target,
        ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
      ].forEach(({childNodes: [...nodes]}) => nodes
        .filter(({nodeType}) => nodeType === document.TEXT_NODE)
        .forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
    };
    
    replaceOnDocument(/€/g, "$");
    
    const replaceOnDocument = (() => {
        const replacer = {
          [document.TEXT_NODE](node, pattern, string){
            node.textContent = node.textContent.replace(pattern, string);
          },
          [document.ELEMENT_NODE](node, pattern, string, {attrs, props} = {}){
            attrs.forEach((attr) => {
              if(typeof node[attr] !== "function" && node.hasAttribute(attr)){
                node.setAttribute(attr, node.getAttribute(attr).replace(pattern, string));
              }
            });
            props.forEach((prop) => {
              if(typeof node[prop] === "string" && node.hasAttribute(prop)){
                node[prop] = node[prop].replace(pattern, string);
              }
            });
          }
        };
    
        return (pattern, string, {target = document.body, attrs: [...attrs] = [], props: [...props] = []} = {}) => {
          // Handle `string` — see the last section
          [
            target,
            ...[
              target,
              ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
            ].flatMap(({childNodes: [...nodes]}) => nodes)
          ].filter(({nodeType}) => replacer.hasOwnProperty(nodeType))
            .forEach((node) => replacer[node.nodeType](node, pattern, string, {
              attrs,
              props
            }));
        };
    })();
    
    replaceOnDocument(/€/g, "$", {
      attrs: [
        "title",
        "alt",
        "onerror" // This will be ignored
      ],
      props: [
        "value" // Changing an `<input>`’s `value` attribute won’t change its current value, so the property needs to be accessed here
      ]
    });
    
    string = new DOMParser().parseFromString(string, "text/html").documentElement.textContent;
    
    <div id="mydiv">
    <!-- you page here -->
    </div>
    
    var html=document.getElementById('mydiv').innerHTML;
    html = html.replace(/this/g,"that");
    document.getElementById('mydiv').innerHTML=html;
    
    document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")
    
    <a href="/i-am/123/a/overpopulation">overpopulation</a>
    
    <a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>
    
            $("*:containsIN('overpopulation')").filter(
                function() {
                    return $(this).find("*:contains('" + str + "')").length == 0
                }
            ).html(function(_, html) {
                if (html != 'undefined') {
                    return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
                }
    
            });
    
        $.extend($.expr[":"], {
            "containsIN": function(elem, i, match, array) {
                return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
            }
        });