1

The below script results in : res = NEW I would like the result to be: res = NEW_okok_NEW

The .+ finds the first START and the last END, but I want it to find the next START and the next/following END, and replace it. How is that possible ?

<script>
$ (function () {
var str = "START_sometext_END_okok_START_someothertext_END"; 
var res = str.replace(/(START.+END)/g,'NEW');
alert(res);
});
</script>

2 Answers2

1

You should make your regex ungreedy, so it matches the less it can instead of the most.

/(START.+END)/g

becomes

/(START.+?END)/g

Now, it stops to the closest END. You can have more explanations about 'greedyness' here

Community
  • 1
  • 1
tomaoq
  • 3,028
  • 2
  • 18
  • 25
0

You need to take the greediness out of your regexp.

str.replace(/START.+?(END)/g,'NEW');

=> "NEW_okok_NEW"

Demo

cracker
  • 4,900
  • 3
  • 23
  • 41
techfoobar
  • 65,616
  • 14
  • 114
  • 135