admin管理员组文章数量:1400771
I have an array full of strings which I'd like to loop over and replace any occurrences of '123' with ''.
The desired result would be: ['hello', 'cats', 'world', 'dogs']
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
arr.forEach(x => {
x.replace('123', '');
});
I have an array full of strings which I'd like to loop over and replace any occurrences of '123' with ''.
The desired result would be: ['hello', 'cats', 'world', 'dogs']
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
arr.forEach(x => {
x.replace('123', '');
});
Share
Improve this question
asked Dec 5, 2020 at 21:48
nandesukanandesuka
7991 gold badge13 silver badges31 bronze badges
2
-
1
const replacedStrings = arr.map(word => word.replace(/123/g, ''))
– Yevhen Horbunkov Commented Dec 5, 2020 at 21:51 -
forEach()
returnsundefined
, you're supposed to useArray.prototype.map()
insted and, by the way, it's better to use.replace(/123/g, '')
if you want to replace all occurrences of unneeded substring – Yevhen Horbunkov Commented Dec 5, 2020 at 21:53
1 Answer
Reset to default 7Use .map
instead, if you can - return the .replace
call in the callback:
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
const result = arr.map(x => x.replace('123', ''));
console.log(result);
If you have to mutate the array in-place, then take the index as well, and assign the .replace
call back to that index in the array:
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
arr.forEach((x, i) => arr[i] = x.replace('123', ''));
console.log(arr);
本文标签: javascriptUsing replace string method inside forEachStack Overflow
版权声明:本文标题:javascript - Using replace string method inside forEach - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744175867a2593996.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论