简体   繁体   中英

Nodejs: How to replace certain characters within an array with other characters in javascript

Say I have an array like this:

['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html']

I just want to replace all of the "\\ \\" characters with "/" and store this into a new array so that the new array should look like this:

['test/test1/test2/myfile.html', 'test/test1/test2/myfile2.html']

How could I go about doing this?

You can use map function of Array's to create a new Array

var replaced = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'].map(function(v) {
  return v.replace(/\\/g, '/');
});

console.log(replaced);

Since you mentioned node.js, you can just use .map :

var replaced = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'].map(function (x) {
  return x.replace(/\\/g, '/');
});

First of all you have to traverse the array using any iteration method.

This will help you with that:

For-each over an array in JavaScript?

I think you can use the replace function of the String object.

For more reference, please go to:

http://www.w3schools.com/jsref/jsref_replace.asp

Hope that helps

var test = ['test\\test1\\test2\\myfile.html', 'test\\test1\\test2\\myfile2.html'];
    for(var i=0;i<test.length;i++) {
    test[i] = test[i].replace(/\\/g,'/');
}
console.log(test);

outputs ["test/test1/test2/myfile.html", "test/test1/test2/myfile2.html"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM