มี 5 วิธี ในการแปลง ค่า (Value) เป็น String คือ
การต่อ String ว่าง (Concatenating empty strings)
Template Strings
JSON.stringify
toString()
String()
ตัวอย่าง
ในตัวอย่างนี้ ใช้วิธีทั้ง 5 ที่กล่าวมา แปลงค่าเป็น String และแสดงผลลัพธ์
<html> <body> <script> const value = 123; document.write((value + '') +" "+typeof (value + '')); document.write("</br>"); document.write((`${value}`) +" "+typeof (`${value}`)); document.write("</br>"); document.write((JSON.stringify(value)) +" "+typeof (JSON.stringify(value))); document.write("</br>"); document.write((value.toString()) +" "+typeof (value.toString())); document.write("</br>"); document.write((String(value)) +" "+typeof(String(value))); </script> </body> </html>
ผลลัพธ์
123 string 123 string 123 string 123 string 123 string