Middle+
// Data about the price of a product received from the server as a number: // 12345678 (the price can be any but in the range from 1 to [phone]) // need to write a function that converts the price to a formatted string like: // 12'345'678
sobes.tech AI
Answer from AI
To format a number with thousands separated by apostrophes, you can use a regular expression or the toLocaleString method with a custom locale. An example with a regular expression:
function formatPrice(price) {
return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "'");
}
console.log(formatPrice(12345678)); // "12'345'678"
Here, \B is a position not at a word boundary, (?=(\d{3})+(?!\d)) looks ahead for groups of three digits, not reaching the end of the string, and inserts apostrophes between them.