Skip to content Skip to sidebar Skip to footer

Replace String Using Regular Expression At Specific Position Dynamically Set

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 s

Solution 1:

You can use this regex:

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

Working demo

enter image description here

Solution 2:

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(newRegExp(escapedPattern,'g'), function(t){ return ++i===3 ? "hello" : t });

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

Solution 3:

Try

$(selector)
.data("r", ["simple text", 3, "hello"])
.text(function (i, o) {
    var r = $(this).data("r");
    return o.replace(newRegExp(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?

Post a Comment for "Replace String Using Regular Expression At Specific Position Dynamically Set"