0

How can I write regular expression to remove double dash -- into single dash - and if string start or end with dash replace with empty string.

var oldString = "abc--xyz--"
var filtered = oldStringt.replace(???????); 

Sample Input >>>> Output

abc--xyz--       >>>>>    abc-xyz
abc---xyz-123    >>>>>    abc-xyz-123
--abc-xyz-123    >>>>>    abc-xyz-123 
0

3 Answers 3

6

How about chaining replaces:

str.replace(/[-]+/g, '-').replace(/[-]+$/g, '').replace(/^[-]+/g, '')

Fiddle here.

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

2 Comments

Upvote! No need for the square brackets, though (at least not in my console JS interpreter).
Why compile and execute 3 regexp’s when only one is needed?
2
oldString.replace(/-+/g,"-").replace(/(^-+)|(-+$)/g,"");

Comments

0

Here is a single regexp that should work:

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

Tests: http://jsfiddle.net/kd9g3/

Now, I know you specifically asked for regexp, but many replaces like this one can be done using arrays as well (and sometimes they are faster):

oldString.split(/-+/).filter(function(e){return !!e}).join('-')

Comments

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.