1

I have a simple JSON on which I would like to replace one string from one property. Let's say this is my JSON :

var values = [
    { id: 10, url: "www.mydomainname.com/images\uploads\xfolder\FILE_NAME.JPG", longitude: 121.256248, latitude: 19347774275 },
    { id: 11, url: "www.mydomainname.com/images\uploads\xfolder\FILE_NAME.JPG", longitude: 121.7534025, latitude: 19347868 },
    { id: 12, url: "www.mydomainname.com/images\uploads\xfolder\FILE_NAME.JPG", longitude: 121.85458, latitude: 1934748775 },
    { id: 13, url: "www.mydomainname.com/images\uploads\xfolder\FILE_NAME.JPG", longitude: 121.5525, latitude: 19317868 }
] 

Now what I would like to do is to replace every \ with a slash / . For example :

from url: www.mydomainname.com/images\uploads\xfolder\FILE_NAME.JPG to url: www.mydomainname.com/images/uploads/xfolder/FILE_NAME.JPG

What I tried was very simple. This is what I tried :

for(i = 0; i < values.length; i++){
    var str = values[i].url;
    var res = str.replace("''\''", "/");
}

But it didn't work. Any help would be highly appreciated, since it's been a while I've been stucked Thanks in advance :)

5
  • you will have to reassign it Commented May 31, 2018 at 1:44
  • 2
    firslty, that isn't JSON - it's a javascript array of javascript objects Commented May 31, 2018 at 1:44
  • 1
    what is "''\''" you'll want a regex for the search value for a start ... values[i].url = values[i].url.replace(/\\/g, '/') Commented May 31, 2018 at 1:46
  • Probably duplicate: stackoverflow.com/questions/4566771/… Commented May 31, 2018 at 1:46
  • 1
    no @MatrixTai - that's replacing / not \ Commented May 31, 2018 at 1:47

2 Answers 2

5

You're never doing anything with res currently. Use a regular expression with a global flag instead:

var values=[{id:10,url:"www.mydomainname.com/images\\uploads\\xfolder\\FILE_NAME.JPG",longitude:121.256248,latitude:19347774275},{id:11,url:"www.mydomainname.com/images\\uploads\\xfolder\\FILE_NAME.JPG",longitude:121.7534025,latitude:19347868},{id:12,url:"www.mydomainname.com/images\\uploads\\xfolder\\FILE_NAME.JPG",longitude:121.85458,latitude:1934748775},{id:13,url:"www.mydomainname.com/images\\uploads\\xfolder\\FILE_NAME.JPG",longitude:121.5525,latitude:19317868}];
values.forEach(value => value.url = value.url.replace(/\\/g, '/'));
console.log(values);

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

1 Comment

Sorry for the late acceptance of your answer. It did solve my problem :) @certainperformance
1
for(var i=0; i < arr.length; i++) {
 arr[i] = arr[i].replace(/\\/g, "/");
}

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.