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

3
  • @Hovercraft: javascript!, I've must accepted the wrong tag suggestion withoud reading Commented Sep 28, 2015 at 0:43
  • 1
    Is there a practical reason to favour arrays and regexes over two basic replaces? Commented Sep 28, 2015 at 0: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. Commented Sep 28, 2015 at 1:01

3 Answers 3

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: "\\."

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah you need the second slash because javascript think you're escaping the period before it event gets to the RegExp object.
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.

Comments

0

You can change your fn to this :

function strToArr(str)
{
     var res = str.replace(/\./g, "");
     return res.split(",");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.