0

I am writing a simple replace string with the help of regex. I want to add a new attribute such as "isElm" in every <p> tag. Please refer the below fiddle. If I use regex as /<p>(.*?)<\/p>/g and use replace, it works, but if the <p> tag has an attribute, it does not. However, if I use this regex: /<p([^>]*)>(.*?)<\/p>/g, the replace with attribute works, but without the <p> tag, it does not work. I want to find a generic solution for this. Below are the two cases:

  1. <p>one</p> should change to <p isElm="true">one</p>
  2. <p id='2'>two</p> should change to <p id="2" isElm="true">

Note that for both cases above, the isElm="true" attribute is added after the replace. I do not want to create a DOM or jQuery object. I have to use regex due to some limitations.

Fiddle Link :- http://jsfiddle.net/9VHtR/1/

user593029
  • 511
  • 7
  • 18
  • Stop for a moment and read https://stackoverflow.com/editing-help#code-spans. Then format your inline code accordingly. – Felix Kling Jun 10 '14 at 15:49
  • I just realize I was doing the formatting but since you where doing it i could not save edits. will take care in futuer – user593029 Jun 10 '14 at 15:53
  • FYI, you didn't include a jsFiddle example, even though you reference it (you added a link, but that was to http://jsfiddle.net/, so I removed it). – Felix Kling Jun 10 '14 at 15:56
  • 3
    [Do not try to parse HTML with regex!](http://stackoverflow.com/a/1732454/1048572) Use the DOM instead (when working with JS, you usually already have one). Btw, `isElm` is not a valid HTML attribute. – Bergi Jun 10 '14 at 15:57

1 Answers1

2

I'm not sure why you're overcomplicating it (probably matching whole <p> is your requirement) but you can accomplish your task like follows

var x = '<p>this is text</p>';
x = x.replace('<p', '<p isElm="true" ');
console.log(x);
Ejaz
  • 8,719
  • 3
  • 34
  • 49
  • Ejay that is the hardcode & is not generic. It was a space issue I just realize in regex I thought I have to add "or" operator which I was not sure of how to do that. If someone interested can look at it, with updated fiddle all p tags with & without attribute anywhere in string will be added new attribute "isElm". Fiddle Link => http://jsfiddle.net/9VHtR/1/ – user593029 Jun 10 '14 at 16:17