Split string with commas to new line

前端 未结 6 2088
终归单人心
终归单人心 2021-02-04 19:11

I have a string like

This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day


        
相关标签:
6条回答
  • 2021-02-04 19:30
    <p id="errorMessage">Click | the |button |to |display| the| array| values| 
    after| the| split.</p>
    
    $(document).ready(function () {
    var str = $("#errorMessage").text();
    document.getElementById("errorMessage").innerHTML=str.split("|").join(" 
    </br>"); }
    
    0 讨论(0)
  • 2021-02-04 19:31

    With the built in split and join methods

    var formattedString = yourString.split(",").join("\n")
    

    If you'd like the newlines to be HTML line breaks that would be

    var formattedString = yourString.split(",").join("<br />")
    

    This makes the most sense to me since you're splitting it into lines and then joining them with the newline character.

    Although I think speed is less important than readability in most cases, I was curious about it in this case so I've written a quick a benchmark.

    It seems that (in chrome) using str.split(",").join("\n") is faster than str.replace(/,/g, '\n'); .

    0 讨论(0)
  • 2021-02-04 19:33

    You can use .split() to create an array of all the parts of the string...

    var str = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day';
    
    str.split(',');
      -> ["This is great day", " tomorrow is a better day", " the day after is a better day", " the day after the day after that is the greatest day"]
    

    Now, you can do whatever you want with the different parts. Since you want to join with a new line, you can use .join() to put it back together...

    str.split(',').join('\n');
      -> "This is great day
          tomorrow is a better day
          the day after is a better day
          the day after the day after that is the greatest day"
    
    0 讨论(0)
  • 2021-02-04 19:40

    You could also replace them:

    string.replace(/,/g, '\n');
    
    0 讨论(0)
  • 2021-02-04 19:44

    Without testing on my browser try:

    var MyStr="This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day";
    Var splitedStr = MyStr.split(",");
    
    var returnStr = '';
    for (var i = 0; i < splitedStr.length; i++)
    {
        returnStr += splitedStr[i] + '<br />';
    }
    
    document.write(returnStr);
    
    0 讨论(0)
  • 2021-02-04 19:50
    > a = 'This is great day, tomorrow is a better day, the day after is a better day, the day after the day after that is the greatest day'
    > b = a.split(', ').join('\n')
    
    "This is great day
    tomorrow is a better day
    the day after is a better day
    the day after the day after that is the greatest day"
    
    0 讨论(0)
提交回复
热议问题