问题
I have a string of words (item names) being passed to my front end from the database I have set up. It is all working great, but I in my table in html, I have the item name in a loop, so the item names are stuck together if there is more than one item, like so: Item name1Item name2
I am passing them through to the front end using an ejs loop, and <%= data[i].ITEMNAME %>, which passes the values from the database in that specific row. So they are always changing depending on the item name. An example:
I need them like Item name1, Item name2
I have this in my script so far.
var itemNameSplit = '<%= data[i].ITEMNAME %>';
var splitResponse = itemNameSplit.split(" ");
document.write("<td>" + splitResponse + "</td>")
however, this puts a comma after every word, not the end of the item name, like so:
Item,name,1Item,name,2
when again, I need it like
Item name1, Item name2
its slipping my mind how to do this, thanks in advance for the help! much appreciated:)
回答1:
How about this
var splitResponse = itemNameSplit.split("Item").join(", Item").replace(", ", "");
回答2:
//I misread the problem - this just makes 1 comma in cycle of 2, a space
a="Item,name,1Item,name,2"
b=a.split(",")
c=b.reduce((accumulator, currentValue, currentIndex, array) =>{
return currentIndex % 2 ?(accumulator + " " + currentValue) :(accumulator + "," + currentValue)
})
console.log(c)
//Item name,1Item name,2
来源:https://stackoverflow.com/questions/65501932/splitting-string-values-using-javascript