0

I want to convert <font> element to <span> element like this using regex:

Input:

[some strings...]<span [something]></span><font ...>[sometext]</font>[some strings...]

Output:

[some strings...]<span [something]>[sometext]</span>[some strings...]

Note: The input/output is a string.

In shortly, I want to remove the <font> element and move the contents of that into <span> element keeping the attributes of the <span> element.

I've tried this:

const rx = /<span(.*?)><\/span>([^<\\s]+?|\\s*)<font(?:\\s+[^>]*)?>(.*?)<\/font>/gi;

inputStr.replace(rx, function(match, p1, p2, p3) { return `${p2}<span${p1}>${p3}</span>`; });

However it doesn't work.

Can anyone help me?

yakkisyou
  • 510
  • 7
  • 14
  • 2
    just in case. it would be much more readable, flexible and maintainable if you use DOM traversing instead of text-level substitution. Do you have to use RegExp only? – skyboyer Nov 14 '17 at 08:56
  • I completely agree with @skyboyer [I think a link to this answer in needed](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – George Nov 14 '17 at 08:57
  • @skyboyer Unfortunately, I have to use only regex. :( – yakkisyou Nov 14 '17 at 09:05

2 Answers2

0

Use any ID or class selector if possible, I have used here tag name just for example, if you have a Id selector then remove [0] from code. This or with some modification should work for you

document.getElementsByTagName("font")[0].replaceWith('<span>' + document.getElementsByTagName("font")[0].innerHTML +'</span>')

Using Jquery,

$("YOUR_DOM_SELECTOR").replaceWith('<span>' + $("YOUR_DOM_SELECTOR").html() +'</span>')
Nitin Dhomse
  • 2,524
  • 1
  • 12
  • 24
0

I also agree with @skyboyer, this is not the best way, but if you can use regexp only or if this is a one-time task, you can use a class group specifing to take all chars that are not ">", in this way you can take all the params of the tag span and use it in the font:

var text = 'Some text... <span style="color:red"></span><font style="margin:10px">Hi there!</font> other text <span style="color:blu"></span><font style="margin:10px">doh!</font> final text';
console.log(text.replace(/<span([^>]*)><\/span><font[^>]*>(.+?)<\/font>/gi,'<span$1>$2</span>'));

edited in order to match other tags inside (except other s, obviously)

Roberto Bisello
  • 1,235
  • 10
  • 18
  • What if there are `
    ` or other tags in `[sometext]`?
    – yakkisyou Nov 14 '17 at 09:11
  • ah! you're right, I've not thinked about that case... you just need to change the group inside with one with a lazy operator (.+?), so js will grabs as little as possible before matching the – Roberto Bisello Nov 14 '17 at 09:31