最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I display bullet points properly from a string? - Stack Overflow

programmeradmin4浏览0评论

So I am getting a string containing a bulleted list and its displaying like this:

blah * blah * blah

when I'd like it to display like:

  • blah
  • blah
  • blah

my thinking is that I would break the string into an array, run through it in a for loop and splice in a new line right before the point. then just return it .toString()

var charArry = userInfo.split('');
for (var i = 1; i < charArry.length; i++) {
if (i == '\u2022') 
charArry.splice(i, 0, '\n');
}
return charArry.toString();

but maybe that's a terrible approach. any ideas?

So I am getting a string containing a bulleted list and its displaying like this:

blah * blah * blah

when I'd like it to display like:

  • blah
  • blah
  • blah

my thinking is that I would break the string into an array, run through it in a for loop and splice in a new line right before the point. then just return it .toString()

var charArry = userInfo.split('');
for (var i = 1; i < charArry.length; i++) {
if (i == '\u2022') 
charArry.splice(i, 0, '\n');
}
return charArry.toString();

but maybe that's a terrible approach. any ideas?

Share Improve this question asked Jan 18, 2021 at 22:32 Mpsteve137Mpsteve137 491 gold badge2 silver badges4 bronze badges 2
  • &bull; is the special "code" for the bullet. However, trying to format your html with newlines is inheriently flawed, as at a certain point, the browser will ignore whitespace. You need to think in terms of how to convert the string to html – Taplar Commented Jan 18, 2021 at 22:34
  • 1 Don't use explicit bullet characters, use <ul> and <li> – Barmar Commented Jan 18, 2021 at 22:37
Add a ment  | 

2 Answers 2

Reset to default 7

Split the string on "\u2022" and then use <ul> to display bullets.

let str = "blah•blah•blah";

let strArr = str.split("\u2022")

If you really want to add bullets to the string only then you may do something like this:

let newStr = '\u2022' + strArr.join("\n\u2022");

Instead of writing things out in text format, create li elements and append them to a ul element.

let userInfo = 'blah1 blah2 blah3'
var charArry = userInfo.split(' ');
let ul = document.querySelector('#ul')
charArry.forEach(liTxt => {
  let li = document.createElement('li')
  li.innerHTML = liTxt
  ul.appendChild(li)
})
<ul id='ul'></ul>

发布评论

评论列表(0)

  1. 暂无评论