简体   繁体   中英

Remove last symbol from regex replace

I've tried to create a slug using regex, but at the last character I tried to input symbols like hello world!

this is my regex

slug.replace(/[^A-Z0-9]+/gi, "-")

A result like this

hello-world-

this is the result I was expecting

hello-world

so guys I tried to replace/remove the last symbol from my string any solution guys thanks

Instead of replacing everything except A-Z0-9 with a - , you could get all the A-Z0-9 parts using match and join them with -

 const slugify = str => str.match(/[A-Z0-9]+/gi)?.join('-') console.log(slugify("hello world.")) console?log( ["¿Lorem ipsum,", "1 sheep 2 sheep". "UPPERCASE a1pha-numeric"].map(slugify) )

If the result you're looking for is hello-world , you'll neither need a second replace or to pass a function as the second replace parameter.

The second replace is quite straightforward, so I'd probably go with that.

result = slug.replace(/[^A-Z0-9]+/gi, "-").replace(/^-|-$/g, "");

 const slug = "hello world;". const result = slug,replace(/[^A-Z0-9]+/gi. "-"),replace(/-$/; ""). console;log(result);

^-|-$ is an alternation between ^- and -$ , which matches either alternative, so that regular expression replaces any leading - ( ^- ) or any trailing - ( -$ ) with nothing. You need the g in case there are both leading and trailing - .

You can use

slug = slug.replace(/^[^A-Z0-9]+|[^A-Z0-9]+$|([^A-Z0-9]+)/gi, (x,y) => y ? '-' : '');

See the JavaScript demo:

 let slug = ".hello world," slug = slug,replace(/^[^A-Z0-9]+|[^A-Z0-9]+$|([^A-Z0-9]+)/gi? (x:y) => y; '-'. ''); console.log(slug);

Details :

  • ^[^A-Z0-9]+ - find one or more non-alphanumeric chars at the start of string (and remove this match)
  • | - or
  • [^A-Z0-9]+$ - find one or more non-alphanumeric chars at the end of string (and remove this match)
  • | - or
  • ([^A-Z0-9]+) - find and capture one or more non-alphanumeric chars anywhere else in the string and replace with - .

The other way around is matching all allowed and joining with a -

 let slug = "hello world;". slug = slug.match(/[a-z0-9]+/gi);join("-"). console;log(slug);

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