-1

I would like to know how to replace an irregular expression in javascript.I have tried what I have read on stackoverflow but its not working yet. I would like to replace all + with spaces.Here is my code

<script>
String.prototype.replaceAll = function(find,replace){
    var str= this;
    return.replace(new RegExp(find.replace(/[-\/\\^$*?.()|[\]{}]/g, '\\$&'),'g'), replace); };

$(document).ready(function(){
    $('#myform').submit(function(){ 
        var selectedItemsText = '';
        $(this).find('input[type="checkbox"]:checked').each(function(){
            selectedItemsText += $(this).val() + '\r';

        });
            selectedItemsText=selectedItemsText.replaceAll('+',' ');

         if (confirm("Are you sure you would like to exclude these folders(s)?"+selectedItemsText))
        {
            $.ajax({
                type:"POST",
                url:catalog2.php,
                data:$('#chk[]').val(),



                   });      
            }           

            return false;
    });
});

</script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
mina
  • 35
  • 5

2 Answers2

4

Actually you can use a better solution:

var rep = str.replace(/\+/g, " ");

Remember you need to escape the + as it is a reserved word. For an explanation:

/\+/g
  \+ matches the character + literally
  g modifier: global. All matches (don't return on first match)
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

According to What special characters must be escaped in regular expressions?, you should escape .^$*+?()[{\| outside character classes and ^-]\ inside them

That is,

String.prototype.replaceAll = function(find, replace) {
  return this.replace(
    new RegExp(
      find.replace(/[.^$*+?()[{\\|^\]-]/g, '\\$&'),
      'g'
    ),
    replace
  );
};
'a+b'.replaceAll('+', ' '); // "a b"

However, consider the shorter

String.prototype.replaceAll = function(find, replace) {
  return this.split(find).join(replace);
};
'a+b'.replaceAll('+', ' '); // "a b"
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513