繁体   English   中英

Node.js:如何用javascript中的其他字符替换数组中的某些字符

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

说我有一个像这样的数组:

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

我只想用“ /”替换所有“ \\ \\”字符并将其存储到新数组中,以便新数组看起来像这样:

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

我该怎么做呢?

您可以使用Array的map函数创建一个新的Array

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

console.log(replaced);

既然您提到了node.js,就可以使用.map

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

首先,您必须使用任何迭代方法遍历数组。

这将帮助您:

在JavaScript中逐个遍历数组?

我认为您可以使用String对象的replace函数。

有关更多参考,请访问:

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

希望能有所帮助

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);

输出[“ test / test1 / test2 / myfile.html”,“ test / test1 / test2 / myfile2.html”]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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