25

i need to replace a part of a string in Javascript

The following example should clarify what i mean

var str = "asd[595442/A][30327][0]";
var strToReplace = "30333";

var strDesiredResult = "asd[595442/A][30333][0]";

Basically it means the second area within the brackets should get replaced with another string

How to do that?

What i did so far is something like this :

var str = "asd[595442/A][30327][0]";
var regex = /asd\[(.*)\]\[(.*)\]\[(.*)\]/;
var arrMatches = regex.exec(str);

The string appears in arrMatches[2] correctly, and i could replace this. But what happens if in arrMatches[1] is the same string ?

Because it should only replace the value in the second bracket area.

3
  • 8
    and again a downvote on a question of mine in a short time - i've asked a total of 5 questions here on this platform and everyone of them got downvoted in the last couple days, at least provide an explanation ... Commented Mar 5, 2018 at 7:30
  • 1
    I think you were downvoted because your question is not very clear. Commented May 6, 2018 at 19:34
  • 5
    The question is extremely clear Commented Jul 20, 2020 at 21:35

4 Answers 4

22

You may use a regex that will match the first [....] followed with [ and capture that part into a group (that you will be able to refer to via a backreference), and then match 1+ chars other than ] to replace them with your replacement:

var str = "asd[595442/A][30327][0]";
var strToReplace = "30333";
console.log(str.replace(/(\[[^\]]*]\[)[^\]]*/, "$1" + strToReplace));

var strDesiredResult = "asd[595442/A][30333][0]";
console.log(strDesiredResult);

The /(\[[^\]]*]\[)[^\]]*/ has no gmodifier, it will be looking for one match only.

Since regex engine searches a string for a match from left to right, you will get the first match from the left.

The \[[^\]]*]\[ matches [, then any 0+ chars other than ] and then ][. The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.

Details:

  • ( - a capturing group start
    • \[ - a literal [ symbol (if unescaped, it starts a character class)
    • [^\]]* - a negated character class that matches zero or more (due to the * quantifier)
    • ] - a literal ] (outside a character class, it does not have to be escaped)
    • \[ - a literal [
  • ) - end of capturing group #1 (its value can be accessed with $1 backreference from the replacement pattern)
  • [^\]]* - 0+ (as the * quantifier matches zero or more occurrences, replace with + if you need to only match where there is 1 or more occurrences) chars other than ] (inside a character class in JS regex, ] must be escaped in any position).
Sign up to request clarification or add additional context in comments.

4 Comments

this is really sick ;)it looks like it works and beside your explanation i've no idea why this works, but i'll try to understand this for future things - thx dude
Please let me know what is unclear. The point I was making is that you need to rely on a [^...] construct, a negated character class that matches any char but those defined in the class. If you use .* or even .*?, the . can match [ and ], and overmatch, or result in an incorrect match.
the reason why i said i've no idea whats going on is because i'm absolutely inexperienced in this kind of regex world - but i'm certainly willing to study this masterpiece ;)
I will add a full pattern explanation in a couple of minutes.
1

There are many ways to do this. One possible pattern is

str.replace(/^(.+)(\[.+\])(\[.+\])(\[.+\])$/, `$1$2[${strToReplace}]$4`)

You can see that $<number> is referred to captured string from regex (string groups in parentheses). We can refer to those and rearrange it however we want.

2 Comments

This won't help if there are more than 3 [...] substrings in the input string.
Then you can use this pattern instead /^(.+)(\[.+\])(\[.+\])(.*)$/. That's why I said there are many ways. It depends on the context.
1

Use this pattern:

'asd[595442/A][30327][0]'.replace(/^(asd\[[^\[\]]+\]\[)([^\[\]]+)(\]\[0\])$/, '$130333$3')

Test here

^            - match beginning of string
first group  - match "asd[", any chars except [ and ], "]["
second group - match any chars except [ and ]
third group  - match exactly: "][0]"
$            - match end of string

Comments

0

You can use Regular Expression like this /\[[0-9]+\]/ as below.

var str = "asd[595442/A][30327][0]";
var strToReplace = "30333";

var strDesiredResult = str.replace(/\[[0-9]+\]/, '[' + strToReplace + ']'); 

console.log(strDesiredResult);  //"asd[595442/A][30333][0]";

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.