Karem
Karem

Reputation: 18123

replacing specific parts of a string

I have the following string:

dynamic[elements][0][slider][image1]

Which also could be:

dynamic[elements][0][slider][image1]
dynamic[elements][0][abc][image1]
dynamic[elements][0][static][image1]
dynamic[elements][0][fronter][image1]
dynamic[elements][0][xyz][image1]

That I would like to first change "dynamic" to "main" and then slider,abc,static,fronter or xyz (or something completely different) to "value"

So the solution I am looking for should return:

main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]
main[elements][0][value][image1]

How can this be accomplished? I am thinking that a pregex that targets the third [] could be a solution, so I tried the following:

var line = 'dynamic[elements][0][value][image1]';
line.replace('dynamic', 'main');
line.replace(/\[.*?\]/g, 'value');

But I dont know how to replace the third brackets content and the above try doesn't really work.

Upvotes: 0

Views: 49

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

You may use

.replace(/^[^\][]*(\[[^\][]*]\[\d+]\[)[^\][]*(].*)/g, 'main$1value$2')

See the regex demo.

Details:

  • ^ - start of string
  • [^\][]* - 0+ chars other than [ and ]
  • (\[[^\][]*]\[\d+]\[) - Group 1 matching:
    • \[ - a literal [
    • [^\][]* - 0 or more chars other than [ and ]
    • ]\[ - a literal ][ substring
    • \d+ - 1 or more digits
    • ]\[ - a literal ][ substring
  • [^\][]* - 0+ chars other than [ and ]
  • (].*) - Group 2 matching ] and then any 0+ chars other than line break chars.

Note: the ] inside a character class must be escaped, while when outside of the character class, it does not have to be escaped.

The main$1value$2 is the replacement pattern inserting main at the start, then pasting Group 1 contents (with the $1 backreference), then inserting value and then the contents of Group 2.

var ss = ['dynamic[elements][0][slider][image1]', 'dynamic[elements][0][abc][image1]', 'dynamic[elements][0][static][image1]', 'dynamic[elements][0][fronter][image1]', 'dynamic[elements][0][xyz][image1]'];
var rx = /^[^\][]*(\[[^\][]*]\[\d+]\[)[^\][]*(].*)/g;
var subst = "main$1value$2";
for (var s of ss) {
 console.log(s, "=>", s.replace(rx, subst));
}

Upvotes: 3

Related Questions