Reputation: 5974
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([".", ","],["", ", "]));
Upvotes: 2
Views: 121
Reputation: 441
You can change your fn to this :
function strToArr(str)
{
var res = str.replace(/\./g, "");
return res.split(",");
}
Upvotes: 0
Reputation: 10027
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.
Upvotes: 0
Reputation: 59437
The first thing you're trying to replace is a period ("."
), which is a regular expression for any character. You need to escape it: "\\."
Upvotes: 3