flyersun
flyersun

Reputation: 917

Regular Expression to replace part of a string

I need to replace part of a string, it's dynamically generated so I'm never going to know what the string is.

Here's an example "session12_2" I need to replace the 2 at the end with a variable. The "session" text will always be the same but the number will change.

I've tried a standard replace but that didn't work (I didn't think it would).

Here's what I tried:

col1 = col1.replace('_'+oldnumber+'"', '_'+rowparts[2]+'"');

Edit: I'm looking for a reg ex that will replace '_'+oldnumber when it's found as part of a string.

Upvotes: 2

Views: 90

Answers (2)

André Ferrari
André Ferrari

Reputation: 179

If you will always have the "_" (underscore) as a divider you can do this:

 str = str.split("_")[0]+"_"+rowparts[x];

This way you split the string using the underscore and then complete it with what you like, no regex needed.

Upvotes: 4

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17275

var re = /session(\d+)_(\d+)/; 
var str = 'session12_2';
var subst = 'session$1_'+rowparts[2]; 

var result = str.replace(re, subst);

Test: https://regex101.com/r/sH8gK8/1

Upvotes: 0

Related Questions