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'); 

regex tester


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -