Sarfraz
Sarfraz

Reputation: 382861

javascript replace dash char using regex or otherwise

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 ?

Upvotes: 2

Views: 1880

Answers (4)

georg
georg

Reputation: 215029

This looks cleaner to me:

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

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

Upvotes: 0

VisioN
VisioN

Reputation: 145458

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/

Upvotes: 1

Dagg Nabbit
Dagg Nabbit

Reputation: 76776

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

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

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

Upvotes: 4

kalisjoshua
kalisjoshua

Reputation: 2496

Close but forgot the final condition:

and ending dash should be removed if any.

So use this instead:

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

Upvotes: 1

Related Questions