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.

1
  • 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 Commented Aug 14, 2014 at 19:23

3 Answers 3

2

You can use this regex:

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

Working demo

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

And can you do that in JavaScript ?
I get it that you didn't really test... Try and write the replace function with your regular expression...
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.

1 Comment

Excellent, a LAMBDA callback expression!
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.