简体   繁体   中英

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/

You need to use capturing groups.

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

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

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

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

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);

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM