0

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.

2
  • 1
    Note that the array is useless here as all it's elements are inside a-z. This demo change the example a bit to show it works. Commented Jun 24, 2012 at 18:41
  • Is the pCharArray every going to have non a-z characters? ...like @gdoron said... Commented Jun 24, 2012 at 18:41

2 Answers 2

4

You can use this:

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

Note:

Var => var (lowercase)

Live DEMO

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

3 Comments

This will do the opposite: 0-9 and a-z and any character in pCharArray will be removed.
Why downvote answers with typos instead of just commenting the issue? Will never know, I suppose. Upvoted.
Thanks you, your answer is true, but in first edit that i tested your code and @bjornd code ,bjornd code works for me.
3

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

5 Comments

Nice, but if OP adds some metachars inside the array (such as -) it may require escaping depending on its position. +1
@FabrícioMatté Actually only \ and ] should be escaped, all other characters will be treated as control once only at first position.
@bjornd. What about \ / [ ] - chars?
@gdoron As I noted only \ and ] are problematic and should be escaped.
I always have trouble understanding what really requires escaping inside character classes, but still, how come - doesn't need escaping (of course, if it's at beginning or end of the character class it won't require escaping), but if I have "[0"+"-"+"9]", wouldn't it create a [0-9] interval?

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.