0

I would like to replace opening and closing tag, leaving the content of tags and its attribute intact.

Here is what I have:

<div class="QText">Text to be kept</div>

to be replaced with

<span class="QText">Text to be kept</span>

I tried this expression which finds all expressions I want but there seems to be no way to replace found expressions.

<div class="QText">(.*?)</div>

Thanks in advance.

Code Jockey
  • 6,611
  • 6
  • 33
  • 45
AlexShevyakov
  • 425
  • 7
  • 18

3 Answers3

2

Just replace div.

var s="<div class='QText'>Text to be kept</div>";
alert(s.replace(/div/g,"span"));

Demo: http://jsfiddle.net/9sgvP/

Mark it as answer if it helps ;)

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
2

I think @AmitJoki's answer will work well enough in certain circumstances, but if you only want to replace div elements when they have an attribute or a specific set of attributes, then you would want to use a regex replacement with backreferences - how you specify and refer to a backreference, unfortunately, depends upon your chosen editor. Visual Studio has the most unique and annoying "flavor" of regex I know of, while Dreamweaver has a fairly typical implementation (both as well as I imagine whatever editor you're using do regex replacement - you just have to know the menu item or keystroke to bring up the dialog).

If memory serves, Dreamweaver has replacement options when you hit Ctrl+F, while you have to hit Ctrl+H, so try those.

Once you get a "Find" and "Replace" box, you would put something like what you have in your last example above: <div class="QText">(.*?)</div> or perhaps <div class="(QText|RText|SText)">(.*?)</div> into your "Find" box, then put something like <span class="QText">\1</span> or <span class="\1">\2</span> in the "Replacement" box. A few utilities might use $1 to refer to a backreference rather than \1, but you'll have to lookup help or experiment to be sure.

If you are using a language to run this expression, you need to tell us which language.

If you are using a specific editor to run this expression, you need to tell us which editor.

...and never forget the prevailing wisdom on regex and HTML

Community
  • 1
  • 1
Code Jockey
  • 6,611
  • 6
  • 33
  • 45
1

Posted as requested

If its going to be literal like that, capture what's to be kept, then replace the rest,

Find: <div( class="QText">.*?</)div>
Replace: <span$1span>