Regex add 0 after first decimal - javascript

I am currently learning regex but need this quite urgently.
I have a set of values (10, 19.5, 13.99, 9.09). These formats are fine except for the second value.
My problem is how to rewrite so that 19.5 becomes 19.50 without affecting the other entries i.e (10, 19.50, 13.99, 9.09)
Many thanks guys.

If these are numbers, use toFixed()
If these are strings, you can use
num="19.5"
num.replace(/^(\d+\.\d)$/,"$10");

Search for:
(\.\d)(\D|$)
That's dot followed by one number, then something that isn't a number (or end of string).
Replace with:
$10$2
That's the first capture group, then '0', then the second capture group.
var s = '10, 19.5, 13.99, 9.9';
s = s.replace(/(\.\d)(\D|$)/g, '$10$2');
// s == '10, 19.50, 13.99, 9.90'

For example, iterating each value:
var value = '19.5';
value = value.replace(/^\d+[\.,]\d{1}$/, '$&0');

If you wanted to use RegEx you could do something like:
"10, 19.5, 13.99, 9.09".replace(/^\d+\.\d{1}$/g, function (full) {
return full + "0";
});
This would return "10, 19.50, 13.99, 9.09".

try this
var array = [10, 19.5, 13.99, 9.09];
for(var i=0; i< array.length;i++){
if(/[0-9].[0-9]{1}$/.test(array[i])) array[i] = array[i]+'0';
}
alert(array);
OUTPUT :
10, 19.50, 13.99, 9.09
fiddle : http://jsfiddle.net/M9hZx/

EDITED ANSWER:
<script type="text/javascript">
var num = 19.9;
if(String(num).indexOf('.')>-1)
{
num = num.toFixed(2);
}
alert(num);
</script>
The straight answer is to use ".toFixed(2)", but we verify if it is a decimal so that we don't have results like "10.00"
For further formatting options you have the jquery plugin numberformatter:
http://archive.plugins.jquery.com/project/numberformatter
Here is the project webpage:
http://code.google.com/p/jquery-numberformatter/
The direct link for this library:
http://jquery-numberformatter.googlecode.com/files/jquery.numberformatter-1.2.2.jsmin.js

Related

jquery convert price from 5 decimals to round up to 2 decimals

I have a price number that looks like this: $27,272.70000
I'm trying to make it look like this: $27,272.70
I'm stuck with trying different methods but here is what i've got so far:
jQuery(document).ready(function() {
jQuery('.cart-table-wrapper #shopping-cart-table tbody > tr').each(function() {
var the_sp_subtotal = jQuery(this).find('td.col-total.a-right span.price').text().replace("$", "");
var new_sp_subtotal = parseFloat(the_sp_subtotal).toFixed(2);
console.log(new_sp_subtotal);
});
});
But the result that I get is: 27.00
Here is the fiddle - https://jsfiddle.net/zqe37xsk/1/
Can someone please help me, what I'm doing wrong?
Thank you
To format a currency string properly you could use the toLocaleString function. For this to properly work you have to transform your string into a float.
var price = '27,272.70000';
price = parseFloat(price.replace(/[$,]/g, ""));
console.log(price.toLocaleString('us-EN', {
style: 'currency',
currency: 'USD'
}));
parseFloat("27,272.70") returns 27 because the , in 27,272.70 is no longer part of a number.
As an alternative approach you could replace the part behind the last thousands separator and call toFixed on that. Then you can just join everything back together.
In your each function, use:
const [dollar, ...separatedNumber] = jQuery(this).find('td.col-total.a-right span.price').text().split(/\$|,/);
separatedNumber[separatedNumber.length - 1] = Number(separatedNumber.slice(-1)).toFixed(2);
console.log("$" + separatedNumber.join(","));

Javascript - Remove all char '0' that come before another char

I have many strings like this:
0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...
I would like these to become like this:
1, 2, ..., 10, 11, ..., 100, 101, ...
So I would like to remove all the 0 chars before a different char is present.
I tried with
.replace(/0/g, '')
But of course then it also removes the 0 chars after. Therefore for example 0010 becomes 1 instead of 10. Can you please help me?
You can do
.replace(/\d+/g, function(v){ return +v })
This is the shortes Solution
"0001".replace(/^0+/,""); // => 1
...
// Tested on Win7 Chrome 44+
^ ... starting of the String
0+ ... At least one 0
P.s.: test Regex on pages likes: https://regex101.com/ or https://www.debuggex.com
Update 1:
For one long String
"0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,"") // => 1, 2, 10, 11, 100, 101
// Tested on Win7 Chrome 44+
Examples:
// short Strings
var values = ['0001', '0002','0010', '0011','0100','0101'];
for(var idx in values){
document.write(values[idx] + " -> "+values[idx].replace(/^0+/,"") + "<br/>");
}
// one long String
document.write("0001, 0002, 0010, 0011, 0100, 0101".replace(/(^|\s)0+/g,""));
Previously answered here.
.replace(/^0+(?!$)/, '')
Functionally the same as winner_joiner's answer, with the exception that this particular regex won't return a completely empty string should the input consist entirely of zeroes.
Use regex as /(^|,\s*)0+/g it will select 0's at beginning or followed by , and space
document.write('0001, 0002, ..., 0010, 0011, ..., 0100, 0101,...'.replace(/(^|,\s*)0+/g,'$1'))
Explanation :
(^|,\s*)0+
Debuggex Demo
var text='00101';
var result=parseInt(text);

What's the best way to mask a credit card in JavaScript?

In Node, I need to turn a credit card into something like this before rendering the view layer: ************1234.
Without loops and ugliness is there a utility or one liner for this? The credit card can potentially look one of these ways:
1234567898765432
1234-5678-9876-5432
1234 5678 9876 5432
Here's one way with Ramda and some RegEx:
var ensureOnlyNumbers = R.replace(/[^0-9]+/g, '');
var maskAllButLastFour = R.replace(/[0-9](?=([0-9]{4}))/g, '*');
var hashedCardNumber = R.compose(maskAllButLastFour, ensureOnlyNumbers);
hashedCardNumber('1234567898765432'); // ************5432
Demo : http://jsfiddle.net/7odv6kfk/
No need for a regex:
var cc='1234-5678-9012-3456';
var masked = '************'+cc.substr(-4); // ************3456
Will work for any format provided the last four digits are contiguous.
This is for everyone who said they didn't need another way to mask a credit card. This solution will append the last 4 chars of the card number with asterisk.
var cardNumber = '4761640026883566';
console.log(maskCard(cardNumber));
function maskCard(num) {
return `${'*'.repeat(num.length - 4)}${cardNumber.substr(num.length - 4)}`;
}
jsfiddle example
I use this function that is useful for me, because mask the credit card number and format it in blocks of four characters like this **** **** **** 1234, here the solution:
const maskCreditCard = (card) => {
return card
.replace(/.(?=.{5})/g, "*")
.match(/.{1,4}/g)
.join(" ");
};
Here's plain JavaScript using Regex with lookahead
var cardNumbers = [
"1234567898765432",
"1234-5678-9876-5432",
"1234 5678 9876 5432"
];
console.log(cardNumbers.map(maskCardNumber));
//> ["************5432", "************5432", "************5432"]
function maskCardNumber(cardNumber) {
return cardNumber.replace(/^[\d-\s]+(?=\d{4})/, "************");
};
Unlike AllienWebguy's implementation:
doesn't require an external library
does everything in one replace() call
replaces whatever number of digits with the constant number of asterisks (it should be a bit faster, but it may not be what you want)
supports only described formats (will not work, for example, with "1B2C3D4E5F6G7H89876-5432" or "1234+5678+9876=54-32")
Remove non digits, generate an asterisk string of that length - 4, append the last 4:
var masked = Array(cc.replace(/[^\d]/g, "").length - 3).join("*") + cc.substr(cc.length - 4);
Or to include space/hyphens in the mask:
var masked = Array(cc.length - 3).join("*") + cc.substr(cc.length - 4);

remove all Decimals and single numbers from array / string

so my script generates a big blob of "Piano Notes" which are similar to...
var songNotes = "...";
the large Piano notes content
and my problem is between the piano notes which i need [also in the fiddle] there are empty ",," and decimal numbers.. so i cant figure out how to remove the empty
,, and decimals as big as
"1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3"
and i want them removed except the the needed words which are
var theRightOnes = "s2,as2,cs3,ds3,fs3,gs3,as3,gs3,cs4,ds4,fs4,cs3,as4,gs4,ds5,a2,cs4,b2,c3,a3,ds4,b3,c4,as3,gs2,e3,c3,c4,cs3,ds3,a4,fs3,gs3,as3,g3,f3,b4,c5,a3,d4,as2,e4,g4,d3,b3,b2,f4,a2,d4,e4,cs5,gs1,e2,c2,c3,cs2,ds2,a3,fs2,gs2,as2,g2,f2,b3,c4,a2,d3,as1,e3,g3,d2,b2,b1,f3,a1,d5,e5";
so can anyone give me a clue on how this can be accomplished?
if anyone needs more info then i am ready oblige to do so..
Regards - Adarsh Hegde
var notesArr = songNotes.split(",");
var len = notesArr.length;
while(len--) {
if(!notesArr[len] || !isNaN(parseInt(notesArr[len], 10))) {
notesArr.splice(len, 1);
}
}
songNotes = notesArr.join(",");
I think you want to remove all the numbers from notes.
You can say like bellow
var notes = songNotes.split(",").filter(function(note){
return isNaN(note);
});
console.log(notes);
You can use Array.filter (see MDN) to weed out unwanted values:
var wantedNotes = songNotes.split(',')
.filter(function (v) {
return isNaN(+v) && v.trim().length
});
jsFiddle
just use regular expression,like this:
var a = "1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3";
console.log(a.replace(/\b(\d+(\.\d+)?),+/g,""));

convert string into array of integers

I want to convert the following string '14 2' into an array of two integers.
How can I do it ?
A quick one for modern browsers:
'14 2'.split(' ').map(Number);
// [14, 2]`
You can .split() to get an array of strings, then loop through to convert them to numbers, like this:
var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers
The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:
for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); }
SO...older thread, I know, but...
EDIT
#RoccoMusolino had a nice catch; here's an alternative:
TL;DR:
const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]
WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]
There is a subtle flaw in the more elegant solutions listed here, specifically #amillara and #Marcus' otherwise beautiful answers.
The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...
The problem:
var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]
Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/
The (slightly-less-baller) fix:
var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]
So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...
Hope it saves someone time!
var result = "14 2".split(" ").map(function(x){return parseInt(x)});
An alternative to Tushar Gupta answer would be :
'14 2'.split(' ').map(x=>+x);
// [14, 2]`
In code golf you save 1 character.
Here the "+" is "unary plus" operator, works like parseInt.
First split the string on spaces:
var result = '14 2'.split(' ');
Then convert the result array of strings into integers:
for (var i in result) {
result[i] = parseInt(result[i], 10);
}
The point against parseInt-approach:
There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.
Reasons:
It's working:
var src = "1,2,5,4,3";
var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
var obj = {1: ..., 3: ..., 4: ..., 7: ...};
var keys= Object.keys(obj); // ["1", "3", "4", "7"]
var ids = keys.map(parseFloat); // [1, 3, 4, 7]
var arr = ["1", 5, "7", 11];
var ints= arr.map(parseFloat); // [1, 5, 7, 11]
ints[1] === "5" // false
ints[1] === 5 // true
ints[2] === "7" // false
ints[2] === 7 // true
It's shorter.
It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:
// execution time measure function
// keep it simple, yeah?
> var f = (function (arr, c, n, m) {
var i,t,m,s=n();
for(i=0;i++<c;)t=arr.map(m);
return n()-s
}).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
> f(Number) // first launch, just warming-up cache
> 3971 // nice =)
> f(Number)
> 3964 // still the same
> f(function(e){return+e})
> 5132 // yup, just little bit slower
> f(function(e){return+e})
> 5112 // second run... and ok.
> f(parseFloat)
> 3727 // little bit quicker than .map(Number)
> f(parseFloat)
> 3737 // all ok
> f(function(e){return parseInt(e,10)})
> 21852 // awww, how adorable...
> f(function(e){return parseInt(e)})
> 22928 // maybe, without '10'?.. nope.
> f(function(e){return parseInt(e)})
> 22769 // second run... and nothing changes.
> f(Number)
> 3873 // and again
> f(parseFloat)
> 3583 // and again
> f(function(e){return+e})
> 4967 // and again
> f(function(e){return parseInt(e,10)})
> 21649 // dammit 'parseInt'! >_<
Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt
If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+.
You can then map each element using the Number function to convert it. Note that parseInt will not work (i.e. arr.map(parseInt)) because map passes three arguments to the mapping function: the element, the index, and the original array. parseInt accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaNs in the result. However, Number ignores any arguments other than the first, so it works directly.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]
To remove elements that are not numbers, Array#filter can be used in conjunction with isNaN.
const str = '1\t\t2 3 ab 4 c';
const result = str.split(/\s+/).map(Number).filter(x => !isNaN(x)); //[1,2,3,4]
You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]
With an anonymous function for the callback, you can decide what parameters to use, so parseInt can also work.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]
Just for fun I thought I'd throw a forEach(f()) solution in too.
var a=[];
"14 2".split(" ").forEach(function(e){a.push(parseInt(e,10))});
// a = [14,2]
let idsArray = ids.split(',').map((x) => parseInt(x));
Better one line solution:
var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
answerInt.push(parseInt(item))
});
us the split function:
var splitresult = "14 2".split(" ");

Categories

Resources