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
Barbara StreisandOriginal
2024-12-27 14:34:11564browse

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!"

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]);
}

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!

Statement:
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