[英]Lodash function to modify each element in array of strings
I have the following array: 我有以下数组:
let array = [ "c0709f80b718", "c47b86124fde" ];
What is the fastest lodash function to be able to add the ":" in eacch element of the array to convert to a mac address format. 最快的lodash函数能够在数组的eacch元素中添加“:”以转换为mac地址格式。
Expected output should be: 预期输出应为:
let array = [ "c0:70:9f:80:b7:18", "c4:7b:86:12:4f:de" ];
Use Array.map()
to iterate the array, and a RegExp with String.match()
to split each string, and then join it with :
. 使用
Array.map()
迭代数组,并使用带有String.match()
的RegExp拆分每个字符串,然后使用:
进行连接。
const array = [ "c0709f80b718", "c47b86124fde" ]; const result = array.map(str => str.match(/.{2}/g).join(':')) console.log(result)
As @Akrion suggested, with lodash you can use _.words
with the same RegExp pattern to split the string: 正如@Akrion所建议的,使用lodash可以将
_.words
与相同的RegExp模式一起使用以拆分字符串:
const array = [ "c0709f80b718", "c47b86124fde" ] const result = _.map(array, str => _.words(str, /.{2}/g).join(':')) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.