简体   繁体   中英

How do I select the text and replace it using regex via jQuery?

I've looked at a lot of stack posts and Google results but I can't quite find my answer... I have this snippet of text.

<p>Lorem JohnJones@xyz.com , consectetur adipisicing elit. Eos, doloribus, dolorem iusto blanditiis unde eius illum consequuntur neque dicta incidunt ullam ea hic porro optio ratione repellat</p>

I'm trying to target the email addresses and then underline them. It's important that the body is selected rather than the <p> tag. I've made an expression that I know works since I made it via RegexPlanet .

So far, I have this:

var result = $("body").text();
var newResult =result.replace("\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b", "REPLACED");
console.log(newResult);

But it doesn't seem to work... If you go to this Here and then click JavaScript, you will see the result of input.replace() . That is essentially what I'm after but I'd also like to be able to use jQuery's .css() function.

How can I do this?

I could make it work by using html() instead of text(), changing the regex and reassigning the result to body:

var result = $("body").html();
var newResult = result.replace(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/g, "REPLACED");
$("body").html(newResult);

Instead of using "REPLACED" in the replace function you could use a function to surround the email within a span like this:

var newResult = result.replace(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/g,
    function (x) { return '<span class="underlined">' + x  + '</span>';});

Try this, without quotes on the regex:

var result = $("body").html();
var newResult = result.replace(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/ig, "REPLACED");
console.log(newResult);
//Lorem REPLACED , consectetur adipisicing elit.....

Notes:

Use $("body").html(); instead of $("body").text(); in order to keep the html tags.
Your regex is weak to match emails, try to improve it.


Demo:

http://codepen.io/anon/pen/epBvxG

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