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

6
  • Well, for starters. You're using regex as a search pattern when you shouldn't be. Commented Sep 1, 2022 at 2:56
  • @John is there any way to do this? I mean replace \d Commented Sep 1, 2022 at 3:04
  • 1
    .replaceAll('\\d', '[N]') You have to escape backslash in a string... Commented Sep 1, 2022 at 3:04
  • @Nick in this way, the output is [a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsdsdd which is incorrect Commented Sep 1, 2022 at 3: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. stackoverflow.com/a/10042082/9360315 Commented Sep 1, 2022 at 3:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

the problem is, in the input that I am getting from API , there is \d in the string not \\d
He doesn't need a regex search query to replace a non dynamic token with a literal string.
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]'));

3 Comments

You copied his typo so your snippet doesn't work.
In the string value, I have \d not \\d. your code won't work if you change \\d to \d
'\\d' is you you get a backslash before a d. Go ahead and put '\d' in the console, it will just output d.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.