0

I need to replace a string only after 3 occurences of '-'. Can someone give me a pattern for it?

ex: xxyy-xxyy-xxyy-xxyy where xx can be more than one character or number and I need to replace the last set of characters.

finalString = String.replace(/xx$/m, "z")

and this doesn't work because I don't know the last set of characters.

Thanks in advance.

3
  • 1
    @PraveenJeganathan: That is for vim, will the regex in that answer work for Javascript as well? Commented Jan 29, 2014 at 15:04
  • 1
    @PraveenJeganathan: Vim regex != Javascript Regex Commented Jan 29, 2014 at 15:04
  • 1
    @anubhava Ohh I missed it. I have retracted my close votes. Thanks. Commented Jan 30, 2014 at 3:37

3 Answers 3

1

You can do:

var s = 'xxyy-xxyy-xxyy-xxyy';
var r = s.replace(/^((?:[^-]*-){3}).*/, '$1foo');
//=> xxyy-xxyy-xxyy-foo
Sign up to request clarification or add additional context in comments.

2 Comments

First of all, thanks. This is almost perfect but I don't want to replace the whole set of characters just the XX part. //=> xxyy-xxyy-xxyy-fooyy
Another tip: this should search for the 'xx' after the last '-' (last '-' or third '-' because I that the string will only have 3 '-').
0

How about:

finalString = String.replace(/xx([^-]+)$/m, "z$1")

3 Comments

Thanks and again, it's almost there. it replaces everything after the last '-' but I need //=> xxyy-xxyy-xxyy-fooyy
No, I will try to explain me better. After the last '-' there will be a set of characters. I know that will start by 'xx' (this is what I want to replace) but after there will be more characters that I want to remain there and I don't know which characters are. Is it clear?
@JayJay: Ok, I see. Have a try with my modified answer, it'll replace last xx by z, keeping the rest unchanged.
0

This is something i took from anubhava's answer, hope this is what you required

var s = 'xxyy-xxyy-xxyy-xxyy';
var r = s.replace(/^((?:[^-]*-){3})xx*/, '$1foo');

1 Comment

Athough this question is already answered I confirm that this solution works as well. Thanks.

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.