1

Replace specific character only when within a boundary.

For example replace html entity only when enclosed inside single quotes.

Input:

<i>Hello</i> '<i>How are you</i>'

Output:

<i>Hello</i> '&lt;i&gt;How are you&lt;/i&gt;'
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
Braj
  • 46,415
  • 5
  • 60
  • 76

2 Answers2

3

You can use replace with a callback:

var s = "<i>Hello</i> '<i>How are you</i>'";

var r = s.replace(/('[^']+')/g, function($0, $1) {
                     return $1.replace(/</g, '&lt;').replace(/>/g, '&gt;'); });
//=> <i>Hello</i> '&lt;i&gt;How are you&lt;/i&gt';
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Try it with `Hello 'How are you'`. [HTML can't be parsed with regex](http://stackoverflow.com/a/1732454/1529630). – Oriol Apr 01 '15 at 20:50
  • 1
    This is just a string and I am trying to do same as StackOverflow does. – Braj Apr 01 '15 at 20:55
0

You'll need to use several regular expressions, first capture the text within single quotes, and then replace all occurrences of your character.

var input = "<i>Hello</i> '<i>How are you</i>'";

var quoted = input.match(/'.*'/)[0];

var output = quoted.replace("<", "&lt;").replace(">", "&gt;");

// output == "<i>Hello</i> '&lt;i&gt;How are you&lt;/i&gt;'"
theonlygusti
  • 11,032
  • 11
  • 64
  • 119