简体   繁体   中英

jquery wrap a e-mail address

I have several e-mail addresses in a text, which is saved in a variable. the e-mail addresses are in this format test[-@-]test.com .

Now I want to wrap each e-mail adress with a span element <span>test[-@-]test.com</span> .

How can I do this?

Much better to use a callback function:

var wrap = function(text) {  
    $("#Text").html( function(){  
        var patt1= new RegExp(text, "g");  
        return $("#Text").html().replace(patt1, function(match){return "<strong>"+ match +"</strong>"});  
    });  
};  

As on http://www.javascriptkit.com/jsref/regexp.shtml#replacecallback

If your text is in a variable string, you can just use regular expressions:

str = str.replace(/([a-z]+\[-@-\][a-z]+\.[a-z]+)/g,'<span>$1</span>');

http://jsfiddle.net/mblase75/yjVFj/

Mind you, though, that matching email addresses with regular expressions can be tricky business .

Use to create a new span element like so:

var emailArray = ["test1[-@-]test.com", "test2[-@-]test.com", "test3[-@-]test.com"];
$.each(emailArray, function (index) {
    emailArray[index] = $('<span>' + emailArray[index] + '</span>');
});

For plain-old vanilla JavaScript:

function wrap(text, element) {
    return document.createElement(element).innerText(text);
}

Otherwise, if you're using jQuery, .wrap('span') ( jQuery API )

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