How to use Regular expression in JavaScript to replace a set of characters with an empty string?
Can anybody help me writing a regular expression to replace these characters with a empty string. Character list is given below.
public static char[] delimiters = { ' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', 开发者_JAVA百科'>', '<', '&', '%', '-', '/', '#' };
var in = "...";
var out = in.replace(/[ \r\n?!:;\-(){}\[\]\\'"=@><&%\/#]+/g, '');
I may have missed a couple of characters.
An alternative solution may be to take a white list rather than black list approach:
var out = in.replace(/[^\w]+/g, '');
This will remove anything that isn't a word character, meaning a letter (uppercase or lowercase), digit or underscore.
Here's the regex you want:
var re = /[ \r\n?!;.,`:(){}\[\]\|\'\\~=@><&%-\/#]/g;
For example:
var test = "j a\nv\ra?s!c;r.i,p`t:I(s)A{w}e[s]o|m'e\\~=@><&%-/#";
test.replace(re, '')
>>> "javascriptIsAwesome"
FYI, the general notation for this sort of thing in regular expressions is "/[...]/" - means, "match any character inside the brackets"
Try this:
var delimiters = [' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', '>', '<', '&', '%', '-', '/', '#'],
re = new RegExp("[" + delimiters.join("").replace(/[-\\\]]/g, "\\$&") + "]", "g");
str = str.replace(re, "");
In your case, I would write a function that escapes any character that could have a special meaning in a regexp, applies the regexp and returns the result:
String.prototype.exclude = function(blacklist) {
for(var i=0; i<blacklist.length; i++) {
if(blacklist[i].match(/\W/)) {
blacklist[i] = '\\'+blacklist[i];
}
}
return this.replace(new RegExp('['+blacklist.join('')+']', 'g'), '');
};
var myString = "j a\nv\ra?s!c;r.i,p`t:I(s)A{w}e[s]o|m'e\\~=@><&%-/#";
myString.exclude([' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', '>', '<', '&', '%', '-', '/', '#']);
// returns "JavascriptIsAwesome" which is of course the correct answer
This might be too aggressive.
/[^A-z0-9]/g
精彩评论