Reputation: 2175
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.
Upvotes: 0
Views: 1652
Reputation: 1
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?
Upvotes: 0
Reputation: 382102
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.
Upvotes: 1