2

I'm trying to transform this string

.jpg,.gif,.png

into this (not dots and space after comma)

jpg, gif, png

I thought that something like PHP's str_replace for arrays in JS will do the trick, so I found this post, and specifically this answer. I tried it but is't not working as expected. I'm getting a blank string... Am I doing something wrong?

JS

String.prototype.replaceArray = function(find, replace)
{
    var replaceString = this;
    var regex;

    for (var i = 0; i < find.length; i++)
    {
        regex = new RegExp(find[i], "g");
        replaceString = replaceString.replace(regex, replace[i]);
    }

    return replaceString;
};

var my_string = ".jpg,.gif,.png";

alert(my_string.replaceArray([".", ","],["", ", "]));

Link to jsfiddle

Community
  • 1
  • 1
Matías Cánepa
  • 5,770
  • 4
  • 57
  • 97
  • @Hovercraft: javascript!, I've must accepted the wrong tag suggestion withoud reading – Matías Cánepa Sep 28 '15 at 00:43
  • 1
    Is there a practical reason to favour arrays and regexes over two basic replaces? – Jongware Sep 28 '15 at 00:56
  • hwnd: I don't think this is really the same as the question you linked to. If I'm not mistaken, OP would like to understand why he's getting a blank string instead of the expected output. – rossipedia Sep 28 '15 at 01:01

3 Answers3

3

The first thing you're trying to replace is a period ("."), which is a regular expression for any character. You need to escape it: "\\."

rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • Yeah you need the second slash because javascript think you're escaping the period before it event gets to the RegExp object. – rossipedia Sep 28 '15 at 01:03
0

I just did this:

var target = '.jpg,.gif,.png';
target = target.replace(/\\./g, '');
target = target.replace(/,/g, ', ');

I'm sure it can be done more efficiently, but this will get the job done.

Nocturno
  • 9,579
  • 5
  • 31
  • 39
0

You can change your fn to this :

function strToArr(str)
{
     var res = str.replace(/\./g, "");
     return res.split(",");
}
Amit.S
  • 431
  • 2
  • 9