2

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.

4
  • you need to get the dynamic number after 'session' ? Commented Oct 7, 2015 at 13:34
  • 4
    What's wrong with .replace(/_\d+$/, whatYouNeed)? Commented Oct 7, 2015 at 13:34
  • @raina77ow could you give me a bit more info on how that would work please? Commented Oct 7, 2015 at 13:37
  • 1
    Avoid regex and use André's answer... Commented Oct 7, 2015 at 13:40

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Just a little typo: You would actually be splitting the string, not the screen ;)
Or in translation: col1 = col1.split('_')[0] +"_"+ rowparts[2];
Thanks Markai. And Roko too. That is more like the question.
0
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

1 Comment

there's no need to use a Capture group before the _

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.