2

I have this:

11111-22222-333---444---55--5566--6-----7-

I am using this code:

overlaps.replace(/-{2}/g, '-');

however it does not work, want i am looking for is that multiple instances of - should be replaced with one - and ending dash should be removed if any.

Can anybody tell what i am doing wrong ?

2
  • overlaps.replace(/--+/g, '-').replace(/-+$/g, '-'); Commented May 18, 2012 at 13:29
  • 1
    To explain why your version does not work : replace will scan the string from left to right replacing each occurrence of matching strings. The scan will continue from immediately beyond the replaced string. Hope that helps. Commented May 18, 2012 at 13:47

4 Answers 4

4

There's no need to use two regular expressions. This should work fine.

overlaps.replace(/-+$|(-)+/g, '$1')

http://jsfiddle.net/wJLTB/3/

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

3 Comments

+1 I love it. This is way better than my multiple replace calls. My regex has gotten rusty due to infrequent use.
@kalisjoshua sometimes multiple simple regex will perform better than a single complex one... it's worth testing for performance-critical things.
@GGG I was thinking about the same (about last comment). However, possibly replace callback might be even faster. Really worth testing.
1

Close but forgot the final condition:

and ending dash should be removed if any.

So use this instead:

overlaps.replace(/-+/g, "-").replace(/-+$/, "");

Comments

1

You can use:

overlaps.replace(/-+/g, "-").replace(/-$/, "");

DEMO: http://jsfiddle.net/wJLTB/1/

Another way is to use callback function:

overlaps.replace(/-+/g, function(str, p1, offset) {
    return offset.lastIndexOf("-") == p1 ? "" : "-";
})

DEMO: http://jsfiddle.net/wJLTB/2/

Comments

0

This looks cleaner to me:

overlaps.replace(/-(?=-|$)/g, '')

The expr reads: remove dash followed by another dash or by the end of input.

1 Comment

The lookahead is almost guaranteed to be slower, though. Looks like it's jsperf time. (edit: looks like it's not jsperf time, jsperf is down right now. Maybe it will be jsperf time later).

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.