简体   繁体   中英

Regex replace but ignore last character

I am trying to replace

/ok/how/are

with

$ok, $how, $are

using regex

str.replace(/\/([0-9a-zA-Z]+)/g, '\$$1,')

and result is

$ok, $how, $are, 

I can't use another statement to remove last leading , how can I get desire result without last ,

You can use two captured group, one with end of string anchor another without anchor and replace value accordingly

 let str = `/ok/how/are` let final = str.replace(/\/([a-zA-Z\d]+)$|\/([a-zA-Z\d]+)/g, (_, g1, g2) => g1? `$${g1}`: `$${g2}, `) console.log(final)

If the only function you can use in replace , you can use your pattern and replace the trailing comma with an empty space.

 const regex = /\/([a-z0-9]+)/g; let str = `/ok/how/are`; str = str.replace(regex, "$$$1, ").replace(/, $/, ''); console.log(str);

Another option without a regex could be using a combination of split on a forward slash, map to prepend a dollar sign and join on a comma and space.

To remove the empty entry after split you could use for example .filter(Boolean)

 let str = "/ok/how/are"; str = str.split("/").filter(Boolean).map(x => "$" + x).join(", "); console.log(str)

Several solutions are possible: if it's about replacing / with $ and separating the resulting terms with a comma this may be viable.

A second solution is using named capture groups ( see here and snippet) in your regular expression

 console.log( `$${"/ok/how/are".split("\/").filter(v => /^[0-9a-zA-Z]+$/g.test(v)).join(", $")}` ); // use es2018 named capture groups in regex // ----------------------------------------- console.log( "/ok/how/are".replace(/\/((?<end>\w+$)|(?<within>\w+))/g, (...args) => { const { within, end } = args[args.length-1]; return within? `$${within}, `: `$${end}`; }) );

Here is another variant of lambda/anonymous function based approach in .replace . This regex uses a capture group inside a lookahead that asserts whether we have / ahead of us or it is end of string.

 let str = '/ok/how/are'; var repl = str.replace(/\/([az\d]+)(?=(\/|$))/ig, ($0, $1, $2) => '$' + $1 + ($2? ", ": "")); console.log(repl); //=> "$ok, $how, $are"

Details:

  • \/([az\d]+) : Match / followed by 1+ letter (ignore case) or digit
  • (?=(\/|$)) : Lookahead that asserts presence of / or end of string and captures it in 2nd capture group

  • ($0, $1, $2) : Here $0 will be full matched string and $1, $2 are first and second capture group

  • '$' + $1 : Concatenates $ and 1st capture group
  • ($2? ", ": "") : Use ternary operator it makes a decision whether capture group #2 or $2 is empty or not. If it is not empty then it adds ", " in final output otherwise an empty string is added.

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