DroidOS
DroidOS

Reputation: 8900

A regex to identify spans with given class names

I am in the process of writing a custom BBCode editor (I have excellent reasons for doing this and not using a readymade effort) which generates, amongst other things HTML markup such as

<span class='className'>...</span>

All of this is done and works well. However, I also need to do the reverse transformation from HTML to my BBCode where from time-to-time I need to identify all spans that use a given classname. For example

<span class='classNameA' style='font-family"Arial"'>Span content</span> so I can convert it to my BBCode markup

[font=Arial]Span Content[/font]

I am well aware of the dangers of using regexs to parse any old HTML and that is not my intent. I just need to reverse parse my own HTML tags - with everything else passing through to the BBCode editor display.

To cut a long story short - I am no good with regexs particularly those that require lookaheads etc. I would much appreciate any help with creating a JavaScript regex for this job.

Upvotes: 1

Views: 109

Answers (1)

mplungjan
mplungjan

Reputation: 178265

I suggest you either use Benjamin's suggestion and store the bb codes somewhere.

Alternatives to your regex would be innerHTMl or textContent from

document.querySelectorAll("span.classNameA");

or

document.getElementsByClassName("classNameA");

or if you use jQuery you can use

$(".classNameA").text()

and

$(htmlString).find(".classNameA").each(function() {
  var text = $(this).text(); 
});

without creating a DOM

Upvotes: 1

Related Questions