How can I remove the caret(^) from a string using a RegExp in Javascript?
For some reason, I can't seem to find a good answer for this one.
I have been trying to escape out the caret (\^), and to use the hex, octal, and other codes for the character using \xdd, \dddd, etc...
But 开发者_如何学JAVAmy replace regexp won't replace the caret (^) with anything. It seems to simply break the expression.
Here is the code I am using:
var field,myExp;
// \x5E is supposed to represent the caret in Hex...
myExp = / *[^a-z^A-Z^0-9\s\x5E]/gi;
field = field.replace(myExp,"");
alert(field);
Help!
The code snippet you gave is rather confusing, but based on the title of the question, if you just want to replace the character ^ with something else, that can be achieved like this...
var str1 = "test^123";
var str2 = str1.replace(/\^/g, "\x005E");
alert(str2);
A character group beginning with ^
is an exclusionary group, and will match every character that isn't in the []
.
If you're trying to remove any letter, number, or ^
, change the regex to
myExp = / *[a-zA-Z0-9^\s]/gi;
When you have the caret as the first character in a [] set, it means "not" - but only at the start. So your regexp means "(spaces followed by) anything that's not a-z, or caret, or A-Z, or caret, or 0-9 etc". Remove all but the first caret and you may have more luck :-)
I found the answer, but you guys all helped me get there. Thanks!
I think what was happening was that my exlude (^) was used too many times and so was creating an exclusion of my exclusionary groups... Since there were no separators between the groups, the first one does the trick.
ORIGINAL: repExp = / *[^a-z^A-Z^0-9]/gi;
FINAL REGEXP: repExp = / *[^a-zA-Z0-9]/gi;
The above filters out anything that is not a leter (a-zA-Z) or number (0-9) from a string.
Thanks, people!
P.S. The space after the initial "/" is there because for some reason, Dreamweaver sees it as the beginning of a comment. :-(
Are you trying to replace or keep all a-z, A-Z, 0-9, whitespace, and carats?
If you're trying to keep them, only use one ^ at the very beginning of the expression like so:
[^a-zA-Z0-9\s^]
If you're trying to replace them all including carat, use:
[a-zA-Z0-9^\s]
Edit (updated answer in response to comment):
Use
[^a-zA-Z0-9]
to match and replace all characters that are not a-z, A-Z, 0-9.
Note: You should use the same expression server-side to validate these form fields, as people could have javascript disabled, or just mess with the POST value to mess with your database.
精彩评论