Home > OS >  How to replace span tags with its own class name inside paragraph
How to replace span tags with its own class name inside paragraph

Time:05-08

I want to replace all <span></span> tags with their own class name inside the dynamic paragraph.

Example:

My paragraph is: "Welcome <span ></span> to our home <span ></span>"

And I want the result: "Welcome 1f4a9 to our home 1f47b"

So I tried many ways but can't be got the class name of span. The paragraph comes from an ajax request as a text format for my public comment section and I will show it also as a push notification.

I tried

spantoemo('Welcome <span ></span> to our home <span ></span>');
function spantoemo(MSG){
var element = $(MSG);   
element.find("span").each(function(index) {
        var A = $(this).attr('class');
        var B = A.replace("emo ", ""); 
        //var JAVACODE = toUTF16(parseInt( A, 16 )); var FINAL =  html.replace(/<span ><\/span>/g, JAVACODE);
        var FINAL =  html.replace(/<span ><\/span>/g, B);
});
var newString = element.html(); //get back new string
alert(newString);
}

And fiddle

CodePudding user response:

function replaceSpans(string) {
    return string.replace(/<span ><\/span>/g, '$1');
}

This seems to be giving the results you want.

Putting it into your example:

spantoemo('Welcome <span ></span> to our home <span ></span>');
function spantoemo(MSG){
    MSG = MSG.replace(/<span ><\/span>/g, '$1');
    alert(MSG);
}
  • Related