Question

i know how to use replace & replaceWith but I need to do something different.

Example string:

<span class="highlight_grey">example:</span> some additional text   
& <span class="highlight_grey">again...</span> and to wrap up some 
regular <span>span.. no class here</span>

Desired result:

[highlight color="default"]example:[/highlight] some additional text   
& [highlight color="default"]again...[/highlight] and to wrap up some   
regular <span>span.. no class here</span>

element.replace doesn't work here because I need to replace the entire wrap and keep the text.
replaceWith also doesn't help me because I need to use the string and again I am replacing
the wrapping element.

Would appreciate your help

Was it helpful?

Solution

EDIT: sorry, I haven't noticed the rest of the string. anyway:

http://jsfiddle.net/WJTb7/4/

HTML:

<div id="test">
<span class="highlight_grey">example:</span> some additional text & <span class="highlight_grey">again...</span>
</div>

and JS:

var oldHtml = document.getElementById('test').innerHTML,
    newHtml;

newHtml = oldHtml.replace(/<span class="highlight_grey">(.*?)<\/span>/gi, '[highlight color="default"]$1[/highlight]')

alert(newHtml);

OTHER TIPS

this example seems heavy handed and I bet it can be reduced to a more prett'ified version. Lordex's is a bit more streamlined. I capture the the spans. probably don't need to.

// of course, for txt - you'd just use document.getElementById('test').innerHTML,
var txt = '<span class="highlight_grey">example:</span> some additional text & <span class="highlight_grey">again...</span><span> .. MORE SPAN TEXT </span>'


 txt.replace(/(\<span class="highlight_grey"\>)(.*?)(\<\/span>)/g,function(_,$1,$2,$3){ return '[highlight color="default"]' + $2 + '[/highlight]';

})

// output
// "[highlight color="default"]example:[/highlight] some additional text & [highlight color="default"]again...[/highlight]<span> .. MORE SPAN TEXT </span>"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top