简体   繁体   中英

Need help in writing code to search phrase in a Webpage

I am developing a js file that will take the search string from the Clipboard and will highlight the phrase in the Web page if that is found.
Here I will copy paste the text from ms word. And I am using below regular expressions to clean word formatting from clipboard text..

   var pure = impure.replace(/“/g, "\"");
   pure = pure.replace(/”/g, "\"");
   pure = pure.replace(/’/g, "\'");
   pure = pure.replace(/‘/g, "\'");
   pure = pure.replace(/–/g, "\-");

and then searching the phrase with the following method

   var body = $('body');
   var replaced = body.html().replace(''+pure+'','<span class="highlight">'+pure+'</span>');
   $("body").html(replaced);

With this I am able to find individual words and some small sentences.. But i am unable to find the total phrase at a time... For example look at this fiddle(This works in only IE, cause i am currently targeting IE).

Please suggest me a good way to proceed further.. Here my Word may contains Bullets, Newlines, Bolds, Italics etc...

I'm not sure what was the exact bug you were having doubts about, but I found some bugs of my own in your script. I fixed them here: http://jsfiddle.net/F7txy/6/

One of the problems is that you appeared to be trying to replace the pure text with pure again:

var replaced = body.text().replace(
    '' + pure + '',
    '<div class="highlight">' + pure + '</div>'
);

It looks like you should have been replacing the impure with pure:

var replaced = body.text().replace(
    '' + impure + '',
    '<div class="highlight">' + pure + '</div>'
);

Also, you can chain the replace methods together (which I did for you). Also, you could combine all of them into one but I'll let you do that.

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