0

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Andreas
  • 545
  • 2
  • 11
  • 24

4 Answers4

1

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

Botz3000
  • 39,020
  • 8
  • 103
  • 127
1

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.

Community
  • 1
  • 1
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
0

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>');
});
sinemetu1
  • 1,726
  • 1
  • 13
  • 24
0

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)

pete
  • 24,141
  • 4
  • 37
  • 51