用一个替换多个连续的连字符

问题描述:

使用Javascript可以实现吗?

Is this possible in Javascript?

我来自Java,但无法在Javascript中使用.

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

s/-{2,}/-/g

还有另一种可行的方法吗?

Is there another way that works?

是的.您可以将同一正则表达式与Javascript replace() 方法.

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

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

示例:

var r = 'foo--bar---baz'.replace(/-{2,}/g, '-');
console.log(r); // "foo-bar-baz"