This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I'm trying to format a number as brazilian currency, but I'm not sure what's going wrong.
function format2(n, currency) {
return currency + " " + n.toFixed(2).replace(^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
}
Taken from the comments: “but its giving me a syntax error..”
You're missing a slash to define a regex literal. Change your return statement to
return currency + " " + n.toFixed(2).replace(/^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
^ Teda, the magic opening slash!
Btw, your regex is too complex IMO and doesn't format correctly. I would just do /\./g to get the matching periods, so your replace statement looks like .replace(/\./g, ",");
Demo
I don't know why you're so keen to use a regular expression for this. The following loop solution should be fine and offers a more general solution:
function formatNumber(num, places, thou, point) {
var result = [];
num = Number(num).toFixed(places).split('.');
var m = num[0];
for (var s=m.length%3, i=s?0:1, iLen=m.length/3|0; i<=iLen; i++) {
result.push(m.substr(i? (i-1)*3+s : 0, i? 3 : s));
}
return result.join(thou) + point + num[1];
}
console.log('R$ ' + formatNumber(12345678.155, 2, '.', ',')); // R$ 12.345.678,16
console.log('R$ ' + formatNumber(12.155, 2, '.', ',')); // R$ 12,16
Related
This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 months ago.
Currently, I got let str = 'prefix' which has length of 6, but I would like to add empty space at the end and update it to str = 'prefix ' with length of 7.
I have tried str.split("").push("").join("") but I get error saying join is not a function.
I have also tried str[str.length] = ' ', but this doesn't work either. What other options do I have?
You can concatenate the strings:
let str = 'prefix';
str = str + ' ';
// str === 'prefix '
or, if you want to pad any sized string to a specified length:
let str = 'prefix';
str = str.padEnd(7, " ");
// str === 'prefix '
This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 4 years ago.
I am attempting to uppercase the output string of a variable value as follows;
I have tried:
document.getElementById('namePlaceholder').innerHTML = name.value.charAt(0).toUpperCase() + ' is here ';
name.value is a user input so my attempt is to uppercase the first letter of name.
example
name.value = james
preferred outcome James is here.
is there a simple javascript solution for this?
You cannot mutate strings directly as you are trying - you have to create a new string by concatenating the pieces you want:
document.getElementById('namePlaceholder').innerHTML =
name.value.charAt(0).toUpperCase() + // will give you "J"
name.value.slice(1).toLowerCase() + // will give you "ames"
' is here ';
In lay terms, the slice(1) part says "grab everything after the first character". In more technical terms, if you have the name James, you can think of it as a series of letters (not an array, but kinda):
['J', 'a', 'm', 'e', 's'].
You can access individual letters like name[0], which will give you "J" and name[3] which will give you "e". You can then do name.slice(1), which will start at "a" and grab everything after it: "ames". To illustrate further, you could do name.slice(-2) to get the last 2 characters: "es". Or, if you want "me", you can do name.slice(2, 4).
Using substring
document.getElementById('namePlaceholder').innerHTML =
name.value.charAt(0).toUpperCase() +
name.value.substr(1) +
' is here ';
Using Regular Expression:
document.getElementById('namePlaceholder').innerHTML =
name.value.replace(/^\w/, c => c.toUpperCase()); + ' is here ';
exactly similar to the following:
document.getElementById('namePlaceholder').innerHTML =
name.value.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
+ ' is here ';
This question already has answers here:
how to extract floating numbers from strings in javascript
(3 answers)
Closed 4 years ago.
I have string like
11.7 km
and I need get only int( 11.7 ), how can I do this with JavaScript?
Thanks.
Try the parseInt().
Example:
var string = "11.7 km";
alert(parseInt(string));
This would alert: "11".
In your case you have a float, so you could use:
alert(parseFloat(string));
This gives an alert with "11.7".
ParseFloat reference
ParseInt reference
You can use replace method by passing a regex expression as argument.
console.log('11.7 km'.replace(/[^0-9.]/g, ''));
Try This.
var numbers = distance.replace(/[^0-9.]/g,'');
alert(numbers);
You can use parseFloat('11.7km') this will return 11.7
You can also use this.
console.log(Number(("11.7 km").replace(/[^\d.-]/g, '')));
This regular expression will match all numerical values in a string, regardless of text before or after the value.
var str = "11.7 km\n" +
"Text before 11.7 km\n" +
"11.7 km Text after\n" +
"Text before 11.7 km Text after\n";
var matches = str.match(/(\.\d*)*\d+(\.\d*)*/igm).map(parseFloat);
console.log('string "' + str + '" has ' + matches.length + " matches:");
console.log(matches);
The solution you can use is a Regular Expression, using the match function:
your_text = "11.7 km";
r = new RegExp("\\d|\\.","g");
matched_number = your_text.match(r);
number = matched_number.join("");
number_float = parseFloat(number)
This question already has an answer here:
Javascript regex match fails on actual page, but regex tests work just fine
(1 answer)
Closed 4 years ago.
I am trying to replace the nth occurrence of a character with the following function
It works for strings of letters but I want to replace the 2nd [ in [WORLD!] HELLO, [WORLD!]
I am trying the pattern /.\\[/ which works in RerEx tester but not in my function. I get no error just no replacement
Thanks
function ReplaceNth_n() {
Logger.log(ReplaceNth("[WORLD!] HELLO, [WORLD!]", "/.\\[/", "M", 2))
}
function ReplaceNth(strSearch,search_for, replace_with, Ocur) {
var nth = 0;
strSearch = strSearch.replace(new RegExp(search_for, 'g'), function (match, i, original) {
nth++;
return (nth === Ocur) ? replace_with : match;
});
return strSearch
}
When you create a regular expression with RegExp, you should not include the opening and closing / in the string, and I also don't understand why you added a . there.
Wrong: new RegExp("/test/");
Correct: new RegExp("test");
So the string passed as parameter for search_for should be \\[.
The nth occurrence.
^([^<char>]*(?:<char>[^<char>]*){<N-1>})<char>
Replace with $1<repl_char>
Where the regex string is constructed
regexStr = '^([^' + char + ']*(?:' + char + '[^' + char + ']*){' + (N-1) + '})' + char;
Where char is to be found and N > 0
How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')