Skip to content
Advertisement

Change Text in Array in Javascript

I have the following list:

    var submenu = localStorage.getItem('SubMenu')
    var submenuList = submenu.split(',');

0: "Ownership"
1: "Skills<br>Dev"
2: "Financing<br/>and ESD"
3: "Socio-Economic<br>Dev"
4: "Access to<br/>Financial Services"
5: "Board Participation"
6: "Employee Structure"
7: "Preferential Procurement"
8: "Enterprise Development"
9: "Supplier Development"

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

submenuList.forEach(word =>{allMenuItems = allMenuItems.replace('Dev','Development')})

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.

submenuList = submenuList.map(
  word => word.replace(
    'Dev',
    'Development'
  )
)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement