0

I want to use regular expression to replace a string from the matching pattern string.

Here is my string :

"this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this."

Now, I have a situation that, I want to replace "just a simple" with say "hello", but only in the third occurrence of a string. So can anyone guide me through this I will be very helpful. But the twist comes here. The above string is dynamic. The user can modify or change text.

So how can I check, if the user add "this is just a simple text" one or more times at the start or before the third occurrence of string which changes my string replacement position?

Sorry if I am unclear; But any guidance or help or any other methods will be helpful.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Sandeep Pal
  • 2,067
  • 1
  • 16
  • 14
  • If possible , can clarify _"So how can I check, if the user add "this is just a simple text" one or more times at the start or before the third occurrence of string which changes my string replacement position?"_ ? What would be the "string replacement position" if "this is just a simple text" was added to the string ? Thanks – guest271314 Aug 14 '14 at 19:23

3 Answers3

2

You can use this regex:

(?:.*?(just a simple)){3}

Working demo

enter image description here

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
1

You can use replace with a dynamically built regular expression and a callback in which you count the occurrences of the searched pattern :

var s = "this is just a simple text. this is just a simple text. this is just a simple text. this is just a simple text. How are you man today. I Have been working on this.",
    pattern = "just a simple",
    escapedPattern = pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
    i=0;
s = s.replace(new RegExp(escapedPattern,'g'), function(t){ return ++i===3 ? "hello" : t });

Note that I used this related QA to escape any "special" characters in the pattern.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Try

$(selector)
.data("r", ["simple text", 3, "hello"])
.text(function (i, o) {
    var r = $(this).data("r");
    return o.replace(new RegExp(r[0], "g"), function (m) {
        ++i;
        return (i === r[1]) ? r[2] : m
    })
}).data("r", []);

jsfiddle http://jsfiddle.net/guest271314/2fm91qox/

See

Find and replace nth occurrence of [bracketed] expression in string

Replacing the nth instance of a regex match in Javascript

JavaScript: how can I replace only Nth match in the string?

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177