Home > Web Front-end > JS Tutorial > How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?

How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?

Barbara Streisand
Release: 2024-12-27 14:34:11
Original
566 people have browsed it

How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?

JavaScript Analogue of printf/String.Format

You seek a JavaScript equivalent to C/PHP printf() or C#/Java String.Format() specifically for number formatting with thousand separators. The Microsoft Ajax library provides String.Format(), but you prefer a lightweight solution.

Current JavaScript

ES6 introduces template strings, offering a concise alternative:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"
Copy after login

Older Solutions

Consider the sprintf() library for JavaScript. Alternatively, implement your own simplified format method as follows:

function format(template, ...args) {
  return template.replace(/{(\d+)}/g, (match, index) => args[index]);
}
Copy after login

This approach avoids successive replacements that can lead to errors when replacement strings contain format sequences.

The above is the detailed content of How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template