Home > Enterprise >  Replace regex value does not work when there is \d in string
Replace regex value does not work when there is \d in string

Time:09-01

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 \\.

CodePudding user response:

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);

CodePudding user response:

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]'));

  • Related