0

First question on here so please be nice :)

I know very little about regular expressions but I am using one in a current project which strips special characters from a string. It looks like this...

newWord = newWord.replace(/[^0-9A-Za-z ]/g, "");

It works well, but I need to modify it slightly so that it doesn't remove the £ (GBP) character.

I've tried several things but without learning regexes from the start I'm just guessing and none of it's working.

Can anyone help?

1
  • regular-expressions.info You can use that site as a quick-reference guide without having to learn anything in great detail. Commented Jan 16, 2009 at 21:25

2 Answers 2

5
newWord = newWord.replace(/[^0-9A-Za-z£ ]/g, "")

or with unicode escape

newWord = newWord.replace(/[^0-9A-Za-z\u00a3\u0020]/g, "")

What you are doing with this regular expression is removing any characters that are not in the list you are providing. The minus character is used to express a range, so any character not in 0-9 (0,1,2,3,..9) A-Z and a-z are replaced by nothing (""). By adding an £ it will no longer replace it with nothing.

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

3 Comments

Triptych had a good point -- outside ASCII, character sets offer no guarantees. You'd be better to use \u00a3.
I'd also recommend using an escape sequence like that for the space character to improve readability because it's easy to overlook it if it's an actual space (I did when I first read the question).
Be sure that both the data and script is encoded with the same encoding. Otherwise the replacement could go wrong. You should better use the Unicode syntax as Jonathan pointed out.
0
newWord = "10 -+-sdf£";
newWord = newWord.replace(/[^0-9A-Za-z £]/g, "");
WScript.StdOut.WriteLine(newWord);

Comments

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.