Dreams
Dreams

Reputation: 8506

How to replace two characters at the same time with js?

Below is my code.

 var str = 'test//123_456';
 var new_str = str .replace(/\//g, '').replace(/_/g, '');
 console.log(new_str);

It will print test123456 on the screen.

My question is how to do it in same regular express? not replace string twice.

Thanks.

Upvotes: 0

Views: 269

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use character class in the regex to match any character in the collection. Although use repetition (+, 1 or more) for replacing // in a single match.

var new_str = str .replace(/[/_]+/g, '');

var str = 'test//123_456';
var new_str = str.replace(/[/_]+/g, '');
console.log(new_str);

FYI : Inside the character class, there is no need to escape the forward slash(in case of Javascript RegExp).

Upvotes: 4

rameshgrg
rameshgrg

Reputation: 21

Use the regex to match the list of character by using regex character class.

var str = "test//123_456";
var nstr = str.replace(/[\/_]/g, '');

Upvotes: 1

Related Questions