I have the following list:
JavaScript
x
14
14
1
var submenu = localStorage.getItem('SubMenu')
2
var submenuList = submenu.split(',');
3
4
0: "Ownership"
5
1: "Skills<br>Dev"
6
2: "Financing<br/>and ESD"
7
3: "Socio-Economic<br>Dev"
8
4: "Access to<br/>Financial Services"
9
5: "Board Participation"
10
6: "Employee Structure"
11
7: "Preferential Procurement"
12
8: "Enterprise Development"
13
9: "Supplier Development"
14
What I want to do is write a forEach
statement in Javascript to replace some certain words with my own hard coded work. For example, where Dev
appears I want to change it to Development
and where Financing<br/>and ESD
I want to change it to Empowerment Financing
I tried the replace
method of my list but that gives me errors because i am getting confused with my forEach
statement
This is what i have tried
JavaScript
1
2
1
submenuList.forEach(word =>{allMenuItems = allMenuItems.replace('Dev','Development')})
2
Advertisement
Answer
forEach
doesn’t allow you to modify each element like that. Put simply, the word
value in your handler is just a value, not a reference to the item in the array. You can either use a for loop to actually get a reference to each element in the array (not recommended), or you can use map
to modify each word instead.
JavaScript
1
7
1
submenuList = submenuList.map(
2
word => word.replace(
3
'Dev',
4
'Development'
5
)
6
)
7