简体   繁体   中英

Replace multi chars - regular expression

i trying to do if there are more then one - in my string its replace to a single - eg.

--- replace to -

or test---demo replace test-demo

my function is

function strconvert( str ) {
  var ret = str;

  ret = ret.replace( /ø/g, 'oe' );
  ret = ret.replace( /Ø/g, 'OE' );
  ret = ret.replace( /å/g, 'aa' );
  ret = ret.replace( /Å/g, 'AA' );
  ret = ret.replace( /æ/g, 'ae' );
  ret = ret.replace( /Æ/g, 'AE' );
  ret = ret.replace( /\_/g, '-' );

  ret = ret.replace(/[^a-zA-Z0-9\/-]/ig,'-').replace(/_+/ig,'-').toLowerCase();

  return ret;
}

You can use replace( /-+/g, '-' );

ret = ret.replace( /-+/g, '-' );

Update : You can combine .replace(/_+/g,'-').replace(/-+/g,'-') to .replace(/[_-]+/g,'-')

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