简体   繁体   中英

JavaScript Replace comma between two characters

hi I am having difficulty creating a regex expression to replace Comma (,) between two characters my string look like this.

let str=Amazon,buy,0123,4213,5424

I want

Amazon buy,0123,4213,5424

I try

str.replace(/\D(,)\D/," ")

but that removes two characters as well

    Amazo uy,0123,4213,5424

If this really is all you want to do, then a regular expression may be overkill. Here's two approaches:

 let str="Amazon,buy,0123,4213,5424"; let newStr = str.replace(",", " "); console.log(newStr);

 let str="Amazon,buy,0123,4213,5424"; let newStr = str.replace("Amazon,", "Amazon "); console.log(newStr);

You have a few answers here that work well, here's another idea depending on the variability of your string:

在此处输入图片说明

What is going on here is:

  1. First get everything up until the first equals sign.
  2. Now capture everything until the first comma ("Amazon").
  3. Now grab everything (buy,01234,4213,5424).

Depending on the complexity of your inputs (spaces, escapes, etc.) this would only go so far but to me it seems like it could work for your situation.

View at: https://regex101.com/r/6wYdUg/1

And another option using a lookbehind with two named capturing groups:

在此处输入图片说明

hi I am having difficulty creating a regex expression to replace Comma (,) between two characters my string look like this.

let str=Amazon,buy,0123,4213,5424

I want

Amazon buy,0123,4213,5424

I try

str.replace(/\D(,)\D/," ")

but that removes two characters as well

    Amazo uy,0123,4213,5424

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