user2688364
user2688364

Reputation: 153

Regular expression to remove more than one continuous "--"

I have two requirements, first, I want to replace the "-" symbol in both beginning and end of the text with an empty value. Second, if there are any continuous "-" symbols they should be replaced with a single "-" symbol.

If possible please provide the code for both the requirements in a single pattern.

CODE:

//1.)
// replace more than 1 "-" in b
// Expected Output : -asdas-sadf-asdasd-ju

var a = "--asdas-sadf----asdasd---ju";
a = a.replace(/-{2,}/,"");
//alert(a);

//2.)
// remove last "-" and starting "-" from b that is "das-" - after das needs to be removed
// Expected output : welcome/asasdgrd/asd-ast-yret-das/456

var b = "-welcome/asasdgrd/asd-ast-yret-das-/456"
b = b.replace(/[-$]/,"");
//alert(b);

Fiddler Link:

http://jsfiddle.net/nj5j0yeq/1/

Upvotes: 1

Views: 232

Answers (3)

macdis
macdis

Reputation: 11

You can check even time of -- and can replace with odd -

var a = "--asdas-sadf----asdasd---ju";
var b= a.split("--").join("-");
var c = b;
var d = c.split("--").join("-");
console.log(d);

or `var res = str.split(/^-+$|(-)+/).join(""); console.log(res);

`

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You need to use capturing groups.

var s = "--asdas-sadf----asdasd---ju";
alert(s.replace(/^-+|-+$|(-)+/gm, "$1"));

Upvotes: 1

vks
vks

Reputation: 67968

^-+|-(?!.*?-)|(-){2,}

You can try this.Replace by $1.See demo.

https://regex101.com/r/jV9oV2/8

Upvotes: 0

Related Questions