Replace string using regular expression at specific position dynamically set

爷,独闯天下 提交于 2019-12-13 07:25:50

问题


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:


You can use this regex:

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

Working demo




回答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(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.




回答3:


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?



来源:https://stackoverflow.com/questions/25311870/replace-string-using-regular-expression-at-specific-position-dynamically-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!