javascript - Improve this recursive search with Regex -
i'm trying improve part of code using regex rather regular replace, clean string submit solr's client.
string.prototype.replacearray = function(find, replace) { var replacestring = this; (var = 0; < find.length; i++) { replacestring = replacestring.replace(find[i], replace[i]); } return replacestring; }; var match = [ '\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ' ]; var replace = [ '\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ' ]; _.map(object, function (field) { field.replacearray(match, replace); });
could exists way use regex instead ?
i tried replace
field.replacearray(match, replace);
to
field.replace(/([\\+-&|!(){}[]^~*?:";])/g, '\\$1');
but doesn't work because don't understand enough how regex works :(
you need escape square brackets. put hyphen @ end because in second place indicates range:
field.replace(/([\\+&|!(){}\[\]^~*?:"; -])/g, '\\$1');
Comments
Post a Comment