Find and replace specific text characters across a document with JS

javascript find and replace text in html
javascript replace
replace all dots in string javascript
replace all in jquery
html replace text
replace text jquery
replace text on webpage javascript
javascript replace first instance

I'm wondering if there is a lightweight way I could use JavaScript or jQuery to sniff out a specific text character across a document; say and find all instances of this character. And then! Write an ability to replace all instances of this with say a $.

I found this snippet for starters:

var str = 'test: '';

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

Essentially; I am wanting a solution for a one page document. Grab all instances of X and make it XY. Only text characters.


How about this, replacing @ with $:

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

http://jsfiddle.net/maximua/jp96C/1/

Find and replace specific text characters across a document with JS, I'm wondering if there is a lightweight way I could use JavaScript or jQuery to sniff out a specific text character across a document; say € and find all instances of  The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).


My own suggestion is as follows:

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,'€');
}

JS Fiddle demo.

The nativeSelector() function comes from an answer (posted by Anurag) to this question: getElementsByTagName() equivalent for textNodes.

How to Replace All Occurrences of a String in JavaScript, You can use the JavaScript replace() method in combination with the regular expression to find and replace all occurrences of a word or substring inside any string. document.write(newStr);; </script> How to replace character inside a string in JavaScript · How to check whether a string contains a substring in JavaScript. you need to escape the dot, since it's a special character in regex. s2.replace(/\./g, '_'); Note that dot doesn't require escaping in character classes, therefore if you wanted to replace dots and spaces with underscores in one go, you could do: s2.replace(/[.


How to find and replace text dynamically via JavaScript – Random , value, document.getElementById('replacement').value);">. Please excuse the use of the table for the text inputs  Summary. Regular expression string replace is a more powerful mechanism than most developers give JS credit for. Global /g regular expressions and function replacer values are just some of the useful but not as well known features of regular expression patterns and replace(..).


The best would be to do this server-side or wrap the currency symbols in an element you can select before returning it to the browser, however if neither is an option, you can select all text nodes within the body and do the replace on them. Below i'm doing this using a plugin i wrote 2 years ago that was meant for highlighting text. What i'm doing is finding all occurrences of € and wrapping it in a span with the class currency-symbol, then i'm replacing the text of those spans.

Demo

(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("$");

JavaScript replace method to change strings with 6 demos, The JavaScript replace method is used to find and replace a given term in a document. var src_str = ("This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. Upon executing above code, the “rep_term” will be searched in the given A demo to replace all matches by user selected value​. Warning string.replace('string','new string') not replaced all character. You have to use regax replace. For exp: I have a sting old string1, old string2, old string3 and want to replace old to new


Use split and join method

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

here is solution

How to Replace Character Inside a String in JavaScript, How do you find and replace a character in a string in JavaScript? The replace command is an extension of the find command. Use a Find object to loop through a Microsoft Office Word document and search for specific text, formatting, or style, and use the Replacement property to replace any of the items found. Applies to: The information in this topic applies to document-level projects and VSTO Add-in projects for Word


JavaScript String replace() Method, all the occurrence you can use the global ( g ) modifier. With this tool you can replace one part of text with another. First, enter the text pattern you want to replace in search text options, then specify the new content that you want to see in its place in replace text options. This tool is greedy and it will search for all occurrences of the given text fragment and replace them all.


Using find and replace – Word to HTML, How do you replace all occurrences of a character in a string in JavaScript? How to replace all occurrences of a string in JavaScript Find out the proper way to replace all occurrences of a string in plain JavaScript, from regex to other approaches Published Jul 02, 2018 , Last Updated Sep 29, 2019


document.getElementsByTagName, of a specified value, use the global (g) modifier (see "More Examples" below). Replace text that you enter or paste into the Input window with the value that you place into the “Find text” field. This “Replace text” feature is not case sensitive. If you put the word “red” into the “Find text” field you will replace “red” and not “Red” where it appears.