If ids is an array, then just use join:
ids = [1, 2, 3, 4];
val = ids.join(', ');
// val is now "1, 2, 3, 4"
Answer from nd. on Stack OverflowHow can I create a comma-separated string in JavaScript using a for loop without adding a trailing comma? - Stack Overflow
javascript - JS: Add comma to a string - Stack Overflow
javascript - How to add comma in a number in string - Stack Overflow
Add Commas to JavaScript output - Stack Overflow
For this particular use, and to avoid evaluating an extra condition in every iteration, you could start with word before entering the loop, and have the loop make one iteration less. To support times being zero, you'll need to add a condition:
function repeatWord(word, times) {
let result = times ? word : "";
for (let i = 1; i < times; i++) {
result += "," + word;
}
return result;
}
console.log(repeatWord('hello', 3));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You could add a condition and check result. If empty (falsy), take it otherwise take comma for adding.
function repeatWord(word, times) {
let result = "";
for (let i = 0; i < times; i++) {
result += (result && ',') + word;
}
return result;
}
console.log(repeatWord('hello', 1));
console.log(repeatWord('hello', 2));
console.log(repeatWord('hello', 3));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Label doesn't use value to assign values. It uses innerHTML. Try the below.
document.getElementById('result').innerHTML = result;
As pointed out in comments, it is better to use textContent or innerText options to set value (only for plain text) as they are safer than innerHTML.You can use it as shown below.
document.getElementById('result').textContent = result;
or
document.getElementById('result').innerText = result;
innerText property is not supported by FireFox and it uses the textContent property. Hence, the below method will work across browsers.
var resultDiv = document.getElementById('result');
if (typeof resultDiv.innerText === 'string') {
resultDiv.innerText = result;
}
else {
resultDiv.textContent = result;
}
Sources:
- IE8 label update via javascript issue
- 'innerText' works in IE, but not in Firefox
Try this
document.getElementById('result').innerHTML = result;
instead of .value, use .innerHTML
You can specify the exact number of decimal digits in your options, which is the second parameter in toLocaleString()
const number = 24242324.5754;
number.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
// result is: 24,242,324.58
See also MDN doc here
minimumFractionDigits
The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is
maximumFractionDigits
The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3
The toFixed() method returns a string but the toLocaleString() method expects a number so just convert your string to a number after using the toFixed() method with the parseFloat() function and then use the toLocaleString() method on it.
However, do note that you will have to manually append the leading 0 since the parseFloat() method removes any leading zeroes to the right of the decimal point.
Check this particular answer on another Stack Overflow thread that explains the reason why the parseFloat() method removes the leading zeroes after the decimal point.
var num = 66666.7
var parsedNum = (""+num).split('.')[1].length > 1 ?
parseFloat(num.toFixed(2)).toLocaleString() :
parseFloat(num.toFixed(2)).toLocaleString() + '0';
console.log("original", num)
console.log("with comma", num.toLocaleString())
console.log("with 2 digit fixed", num.toFixed(2))
console.log("now working--", parsedNum)
(1234567890).toLocaleString();
function addCommas(nStr)
{
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
http://www.mredkj.com/javascript/nfbasic.html
To integrate:
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = addCommas(count);", msInterval);
Just insert the code to add the comma at the start of the outer looop (i.e. when it loops each set). But include a check for whether there is any previous text in the output, otherwise it'll add a comma before the first entry.
Like this:
const repeatNumbers = function(arr) {
let numbersRepeated = "";
for (let i = 0; i < arr.length; i++) {
if (numbersRepeated != "") numbersRepeated += ",";
for (let j = 0; j < arr[i][1]; j++) {
numbersRepeated += arr[i][0];
}
}
if (arr.length === 0) {
return numbersRepeated;
} else {
return numbersRepeated;
}
}
console.log(repeatNumbers([
[1, 2],
[2, 3]
]));
I would map() the array to new array of the repeating values and use join()
const repeatNumbers = function(arr) {
return arr.map(e => e[0].toString().repeat(e[1])).join(', ')
}
console.log(repeatNumbers([
[1, 2],
[2, 3]
]));
Just split into two parts with '.' and format them individually.
function commafy( num ) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
Simple as that:
var theNumber = 3500;
theNumber.toLocaleString();
As stated in the comments use toLocaleString()
Simple example
let number = 123456789;
let numberWithComma = number.toLocaleString();
console.log(numberWithComma);
Thank you for the help guys!
MileagePointsObj.innerHTML = (parseInt(((RaceLength*60*60)/LapTime)*10 / 10, 10) * 10).toLocaleString()
In JavaScript, you can convert an array to a string with commas using the join()
method.
The join() method returns a string that concatenates all the elements of an array, separated by the specified separator, which in this case is a comma.
Here is an example:
const array = ['apple', 'banana', 'orange'];
const string = array.join(', ');
console.log(string);
// output: "apple, banana, orange"
In this example, we first define an array of three fruits. Then we use the join()
method with a comma and a space as the separator to create a string that lists all the fruits with a comma and a space between each one.
You can replace the comma and space separator with any other separator you like, such as a hyphen, a semicolon, or a newline character.
It's important to note that the join() method only works on arrays, and it will throw an error if you try to use it on any other type of object.
Click here to learn more ways to Convert Array to String with Commas in JS
Simply
return str1 + ", " + str2;
If the strings are in an Array, you can use Array.prototype.join method, like this
var strings = ["a", "b", "c"];
console.log(strings.join(", "));
Output
a, b, c
try this:
function test(str1, str2) {
var res = str2 + ',' + str1;
return res;
}