Hamidreza
Hamidreza

Reputation: 1915

Javascript replace method with both array and regex

How i can replace any character except 0-9 a-z and and array of some characters with '' (nothing).

My code is look like this

Var pCharArray = ['l', 'o', 'c'];//local characters
Var stringOrginal = 'Some Text';
stringOrginal.replace(/(^[0-9][a-z]pCharArray)/g, '');

Every character that is not 0-9 AND not a-z AND not in pCharArray, should be removed.

Upvotes: 0

Views: 96

Answers (2)

bjornd
bjornd

Reputation: 22943

^ character means negation only when used inside of character class, i.e. [^a] means any character except a. When it's used outside of the character class it means the beginning of the string.

Correct code:

stringOrginal.replace(new RegExp("[^0-9a-z"+pCharArray.join('')+"]", 'g'), '');

Also please note if you want to include backslash or closing bracket to the pCharArray array you should state them as '\\' and '\]' there respectively.

Upvotes: 3

gdoron
gdoron

Reputation: 150253

You can use this:

stringOrginal.replace(new RegExp("[^0-9a-z" + pCharArray.join('')+"]", 'g'), "");

Note:

Var => var (lowercase)

Live DEMO

Upvotes: 4

Related Questions