0

I have the below value as a plain text

`[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\d\d`

I want to replace all [a-ZA-Z] with [C] and replace all \d with [N]. I tried to do this with the following code, but it does not work for \d.

value.replace(/\[a-zA-Z\]/g, '[C]').replace(/\\d/g, '[N]').replaceAll('\d', '[N]')

The final result must be:

[C][C][C][C]asass[N][N]

but it output

[C][C][C][C]s[N]s[N]s[N][N]

Note: I am getting this value from API and there is just one \ before d not \\.

osman Rahimi
  • 1,427
  • 1
  • 11
  • 26
  • Well, for starters. You're using regex as a search pattern when you shouldn't be. – John Sep 01 '22 at 02:56
  • @John is there any way to do this? I mean replace `\d` – osman Rahimi Sep 01 '22 at 03:04
  • 1
    `.replaceAll('\\d', '[N]')` You have to escape backslash in a string... – Nick Sep 01 '22 at 03:04
  • @Nick in this way, the output is `[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsdsdd` which is incorrect – osman Rahimi Sep 01 '22 at 03:07
  • 1
    That's not how js strings work. Backslash on its own is an escape character, in order to have one in a string you have to escape it. Two backslashes will result in a single. https://stackoverflow.com/a/10042082/9360315 – AlienWithPizza Sep 01 '22 at 03:16
  • If you get `...\d` from a plain text, you can't just put quotation marks around it and expect the result to be an equivalent string in JS (you need to escape the backslash). – qrsngky Sep 01 '22 at 03:20

2 Answers2

1

The issue here might actually be in your source string. A literal \d in a JavaScript string requires two backslashes. Other than this, your replacement logic is fine.

var input = "[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\\d\\d";
var output = input.replace(/\[a-zA-Z\]/g, '[C]').replace(/\\d/g, '[N]');
console.log(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You have some issues with \d. In the case of '\d' this will just result in 'd'. So maybe you wanted '\\d' as your starting string?

console.log('[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\\d\\d'.replaceAll('[a-zA-Z]', '[C]').replaceAll('\\d', '[N]'));
AlienWithPizza
  • 386
  • 1
  • 8