How do I use replaceWith to replace commas with a linebreak in jQuery?
var team1 = ["player1", "player2", "player3"]
When I prepend the team1 into a table, it shows up like this
player1,player2,player3
So I tried to use jQuery's replaceWith
to somehow replace the comma with a linebreak.
$(team1).replaceWith('<br>')
But that targets the entire team1, and I only want to target the commas or somehow add a linebreak instead of a comma.
Any ideas?
When you coerce an array to a string, you're indirectly using .join(",")
. If you want to join with some other delimiter instead, use join
directly:
str = team1.join("<br>");
But : If the entries in the array are meant to be literal text, not HTML, you first need to escape any characters with special meaning in HTML via map
:
str = team1.map(entry => entry.replace(/&/g, "&").replace(/</g, "<")).join("<br>");
Also note that jQuery's replaceWith
isn't about replacing characters in strings. It's about replacing HTML elements with other HTML elements. To replace characters in a string, you use String's replace
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.