Atural
Atural

Reputation: 5439

How to replace part of a string using regex

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.

Upvotes: 25

Views: 93043

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626826

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).

Upvotes: 22

yivo
yivo

Reputation: 3594

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

Upvotes: 1

Aruna
Aruna

Reputation: 12022

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]";

Upvotes: 0

iboss
iboss

Reputation: 486

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.

Upvotes: 1

Related Questions