Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีใช้ line break ในค่า Array ใน JavaScript

เพื่อเพิ่ม line break ในค่า array สำหรับทุก occurrence ของ ~ ให้ split array ก่อน แล้วค่อยเพิ่ม line break คือ <br> สำหรับแต่ละ ~

ตัวอย่าง:

This is demo text 1!~This is demo text 2!~~This is demo text 3!

จะเพิ่ม line break สำหรับ ~ occurrence:

This is demo text 1! 
This is demo text 2! 
This is demo text 3!

ตัวอย่าง

Live Demo

<!DOCTYPE html> 
<html> 
  <body> 
    <h2>Adding line break</h2> 
    <script> 
      var myArray = 'This is demo text 1!~This is demo text 2!~~This is demo text 3!~This is demo text 4!~~This is demo text 5!'; 
      document.write("Original Array: " + myArray); 
      var brk = myArray.split('~'); 
      var res = brk.join(" <br> "); 
      document.write("<br><br>" + res); 
    </script> 
    <p>Each occurence of ~ adds a line break above.</p> 
  </body> 
</html>

วิธีอื่นๆ

// 1. replaceAll (ES2021) - 直覺กว่า
const result = str.replaceAll('~', '
'); // 2. replace with regex global const result = str.replace(/~/g, '
'); // 3. Template literal สำหรับ multiline จริง const lines = [ 'This is demo text 1!', 'This is demo text 2!', 'This is demo text 3!' ]; const html = lines.join('
');

หมายเหตุ: split('~') จะสร้าง empty string สำหรับ ~~ (สองตัวติดกัน) — อาจต้อง filter: split('~').filter(Boolean)