Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace multiple consecutive hyphens with one

Is this possible in Javascript?

I have this from Java, but can not be used in Javascript.

s/-{2,}/-/g

Is there another way that works?

like image 685
Rafa Tost Avatar asked May 07 '14 04:05

Rafa Tost


2 Answers

Yes it is. You can use the same regex with the Javascript replace() method.

s.replace(find, replacement)
// where 's' is your string object

Example:

var r = 'foo--bar---baz'.replace(/-{2,}/g, '-');
console.log(r); // "foo-bar-baz"
like image 83
hwnd Avatar answered Sep 21 '22 15:09

hwnd


You can just do this:

var newStr = "hi--this is----good".replace(/-+/g,'-'); // hi-this is-good

-+ matches more than 1 - and replaces them with a single -

Your regex is also valid. Except you cannot use s modifier.

like image 20
Amit Joki Avatar answered Sep 18 '22 15:09

Amit Joki