简体   繁体   中英

JavaScript Replace Text with HTML Between it

I want to replace some text in a webpage, only the text, but when I replace via the document.body.innerHTML I could get stuck, like so:

HTML:

<p>test test </p>
<p>test2 test2</p>
<p>test3 test3</p>

Js:

var param = "test test test2 test2 test3";
var text = document.body.innerHTML;
document.body.innerHTML = text.replace(param, '*' + param + '*');

I would like to get:

*test test
test2 test2
test3* test3

HTML of 'desired' outcome:

<p>*test test </p>
<p>test2 test2</p>
<p>test3* test3</p>

So If I want to do that with the parameter above ("test test test2 test2 test3") the <p></p> would not be taken into account - resulting into the else section.

How can I replace the text with no "consideration" to the html markup that could be between it?

Thanks in advance.

Edit (for @Sonesh Dabhi):

Basically I need to replace text in a webpage, but when I scan the webpage with the html in it the replace won't work, I need to scan and replace based on text only

Edit 2:
'Raw' JavaScript Please (no jQuery)

This will do what you want, it builds a regex expression to find the text between tags and replace in there. Give it a shot.

http://jsfiddle.net/WZYG9/5/

The magic is

(\s*(?:<\/?\w+>)*\s*)*

Which, in the code below has double backslashes to escape them within the string. The regex itself looks for any number of white space characters (\\s). The inner group (?:</?\\w+>)* matches any number of start or end tags. ?: tells java script to not count the group in the replacement string, and not remember the matches it finds. < is a literal less than character. The forward slash (which begins an end html tag) needs to be escaped, and the question mark means 0 or 1 occurrence. This is proceeded by any number of white space characters.

Every space within the "text to search" get replaced with this regular expression, allowing it to match any amount of white space and tags between the words in the text, and remember them in the numbered variables $1, $2, etc. The replacement string gets built to put those remembered variables back in.

Which matches any number of tags and whitespace between them.

function wrapTextIn(text, character) {
            if (!character) character = "*"; // default to asterik
            // trim the text
            text = text.replace(/(^\s+)|(\s+$)/g, "");
            //split into words
            var words = text.split(" ");
            // return if there are no words
            if (words.length == 0)
                return;
                // build the regex
            var regex = new RegExp(text.replace(/\s+/g, "(\\s*(?:<\\/?\\w+>)*\\s*)*"), "g");
            //start with wrapping character
            var replace = character;
            //for each word, put it and the matching "tags" in the replacement string
            for (var i = 0; i < words.length; i++) {
                replace += words[i];
                if (i != words.length - 1 & words.length > 1)
                    replace += "$" + (i + 1);
            }
            // end with the wrapping character
            replace += character;
            // replace the html
            document.body.innerHTML = document.body.innerHTML.replace(regex, replace);
        }

工作演示

USE THAT FUNCTION TO GET TEXT.. no jquery required
  1. First remove tags. ie You can try document.body.textContent / document.body.innerText or use this example var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
  2. Find and replace (for all to be replace add 1 more thing "/g" after search)

String.prototype.trim=function(){return this.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');};

var param = "test test test2 test2 test3";

var text = (document.body.textContent || document.body.innerText).trim();

var replaced = text.search(param) >= 0;

if(replaced) {

  var re = new RegExp(param, 'g');

  document.body.innerHTML = text.replace(re , '*' + param + '*');

} else {

//param was not replaced

//What to do here?

}

See here Note: Using striping you will lose the tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM