Home > Software design >  Replace multiple characters with underscore
Replace multiple characters with underscore

Time:07-28

How to use regex to replace all the occurrences of space ( . ) '- with underscores.

I used chaining of replaceAll. Is there a better approach?

const str = "Certificate of Naturalization (From N-550 or N-570) or Certificate of U.S Citizenship (From N-560 or N-561)";
console.log(((str).toUpperCase()).replaceAll(' ', '_').replaceAll('\'', '_').replaceAll('(', '').replaceAll(')', '').replaceAll('-', '_').replaceAll('.', '_'));

CodePudding user response:

You can put the characters you want to replace inside [] and you need to escape some special characters with \

there are 12 characters with special meanings: the backslash , the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign , the opening parenthesis (, the closing parenthesis ), the opening square bracket [, and the opening curly brace {, These special characters are often called “metacharacters”. Most of them are errors when used alone.

If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash.

const str = `Certificate of Naturalization (From N-550 or N-570) or Certificate of U.S Citizenship (From N-560 or N-561)`;

const result = str.replace(/[-'\s\(\)\.]/g, '_')

console.log(result)

  • Related