Using JavaScript's parseInt at end of string - javascript

I know that
parseInt(myString, 10) // "Never forget the radix"
will return a number if the first characters in the string are numerical, but how can I do this in JavaScript if I have a string like "column5" and want to increment it to the next one ("column6")?
The number of digits at the end of the string is variable.

parseInt("column5".slice(-1), 10);
You can use -1 or -2 for one to two digit numbers, respectively.
If you want to specify any length, you can use the following to return the digits:
parseInt("column6445".match(/(\d+)$/)[0], 10);
The above will work for any length of numbers, as long as the string ends with one or more numbers

Split the number from the text, parse it, increment it, and then re-concatenate it. If the preceding string is well-known, e.g., "column", you can do something like this:
var precedingString = myString.substr(0, 6); // 6 is length of "column"
var numericString = myString.substr(7);
var number = parseInt(numericString);
number++;
return precedingString + number;

Try this:
var match = myString.match(/^([a-zA-Z]+)([0-9]+)$/);
if ( match ) {
return match[1] + (parseInt(match[2]) + 1, 10);
}
this will convert strings like text10 to text11, TxT1 to Txt2, etc. Works with long numbers at the end.
Added the radix to the parseInt call since the default parseInt value is too magic to be trusted.
See here for details:
http://www.w3schools.com/jsref/jsref_parseInt.asp
basically it will convert something like text010 to text9 which is not good ;).

var my_car="Ferrari";
var the_length=my_car.length;
var last_char=my_car.charAt(the_length-1);
alert('The last character is '+last_char+'.');
Credit to http://www.pageresource.com/jscript/jstring1.htm
Then just increment last_char

Split the word and number using RegEx.
using parseInt() increment the number.
Append to the word.

Just try to read string char by char, checking its ASCII code. If its from 48 to 57 you got your number. Try with charCodeAt function. Then just split string, increment the number and its done.

Related

Replace the numbers with *

How to replace the last two digits with asterisks using JavaScript
Example: console.log(Math.random()) // 0.6334249899746089 || 0.63342498997460**
I gave you as an example random
To replace the last 2 digits with some characters, firstly convert it to a string and then, using the slice() method, append the characters. You can read more about the slice() method in its MDN Documentation.
let numberAsString = Math.random().toString(); //your number as a string
let result = numberAsString.slice(0, -2) + '**'; //cut and append your asterisks

How to round of prices with comma's instead of dots?

In The Netherlands we use comma's in numbers where in other countries dots would be used. For example we use 39,99 and in other countries 39.99.
In a feed with prices we would have prices with such comma use, but I'm having trouble using those as numbers and rounding them by two digits behind the comma (or behind the dot really).
var num1 = "39,1234";
var num = parseInt(num1);
var n = num.toFixed(2);
console.log(n);
Here is such a number. I would like it to result in 39,12. They way I was thinking is then first use it as a string. Then turn that string into a number and use toFixed to round it of to two digets. But it results in 39,00 instead of 39,12.
Perhaps I'm thinking wrong and I should use some other way to make 39,1234 to be seen as 39.1234 so that it is rounded correctly as a number?
How can I used 39,1234 as a number 39,1234 instead of a string? So that I wouldn't have to go through a feed and replace commas by dots first in all my prices?
Edit: Regex version
Earlier I didn't realize that OP originally wanted it back to the format "xx,xx". This is a more elegant solution:
var num1 = "39,1234";
let n = num1.replace(/(?<=,\d{2})(\d*)$/,"");
console.log(n); //32,12
Regex explanation:
(?<=,\d){2} begins a lookbehind match for , followed by digits \d, 2 of them {2}. Lookbehind matches are not replaced.
(\d*)$ when we've found the lookbehind pattern, we match more digits \d, all * of them, till we reach end of string $. This is the match that will get replaced.
Original Solution
What you want is:
var num1 = "39,1234";
var n = parseFloat(num1.replace(",",".")).toFixed(2);
console.log(n); //39.12
// replaces it back to ",", but now it's a string!
n = n.replace(".",",")
console.log(n); //39,12
Explanation:
First replace "," with "." with replace()
Convert to float (not integer) with parseFloat()
Set to 2 decimal places with .toFixed(2)
Replace "." with ",". But now it's a string!
Note: this will not work if the currency value contains . as a thousandth separator. e.g. "40.200,1576". If that's the case, add another line num1 = num1.replace(".","") to strip out the separator before passing it to the parseFloat(...) line.
Try this
comdecimal= num1.replace(".","")
alert(comdecimal);
dotdecimal= comdecimal.replace(",",".")
alert(dotdecimal);
dotdecimal = Math.round(dotdecimal* 100) / 100;
alert(dotdecimal);
Since you're working with currency, I'd recommend using JS ES6 designated NumberFormat feature. Your code should look like this and be easily reused:
const formatter = new Intl.NumberFormat('nl-NL', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
console.log(formatter.format('145,53'.replace(',','.')));
//"€ 145,53"

How to replace a decimal in a number with a string?

How can I replace a decimal in a number with a string? For example, if I have a number 12.12, how can I take the decimal in that number and replace it with a comma (,) so that the output would be 12,12?
I tried this, but my app crashes because of it:
let number = 12.12
number.replace(/./g, ',');
Thanks.
You cannot use replace on a number, but you can use it on a string.
Convert your number to a string, and then call replace.
Also, the period (.) character has special meaning in regular expressions. But you can just pass a plain string to replace.
const numberWithCommas = number.toString().replace('.', ',');
try this:
var stringnumber = stringnumber.ToString();
var endresult = stringnumber.replace(".",",");
You cannot change the value of a const in javascript.

Regex replace for preceding zero twice in string with different condition

I have string XY4PQ43 and I want regex replace should output XY04PQ0043 in JavaScript. For first number in a string I want zero prefix if its single digit to make it 2 digits and for second number in string I want prefix zeros if its less than 4 digit number. Below output expected for regex.
AB1CD123 => AB01CD0123
MN12XYZ1 => MN12XY0001
LJ99P1234 => IJ99P1234
Any jsfiddle or codepen example preferred
Try this.
function format(text) {
let match = /^(.*?)(\d+)(.*?)(\d+)$/.exec(text);
return [
match[1],
match[2].padStart(2, '0'),
match[3],
match[4].padStart(4, '0'),
].join('');
}
console.log(format('AB1CD123'));
console.log(format('MN12XYZ1'));
console.log(format('LJ99P1234'));
For that given string, you can apply the following regex:
var _str = 'AB1CD123';
_str.match(new RegExp(/([A-Z]{2})([0-9]{1,2})([A-Z]{2})([0-9]{1,4})/))
It outputs an array with values matched starting from 1 to 4, where 2 and 4 are the ones you need to manage. For those values you can apply logic - add leading zeros - by checking their length and merge them afterwards. Try it in browser console.
Note: it works for this specific example. For other examples you need to adjust the length matched.

remove values from a string

Does anyone know how I would remove all leading zeros from a string.
var str = 000890
The string value changes all the time so I need it to be able to remove all 0s before a number greater than 0. So in the example above it needs to remove the first three 0s. So the result would be 890
It looks like we each have our own ways of doing this. I've created a test on jsperf.com, but the results are showing
String(Number('000890'));
is the quickest (on google chrome).
Here are the numbers for the updated test based on #BenLee's comment for Firefox, IE, and Chrome.
See: this question
var resultString = str.replace(/^[0]+/g,"");
var resultString = str.replace(/^[0]+/g,"");
I think a function like this should work
function replacezeros(text){
var newText = text.replace(/^[0]+/g,"");
return newText;
}
If it needs to stay as a string, cast it to a number, and cast it back to a string:
var num = '000123';
num = String(Number(num));
console.log(num);
You could also use the shorthand num = ''+(+num);. Although, I find the first form to be more readable.
parseInt('00890', 10); // returns 890
// or
Number('00890'); // returns 890
If your problem really is as you defined it, then go with one of the regex-based answers others have posted.
If the problem is just that you have a zero-padded integer in your string and need to manipulate the integer value without the zero-padding, you can just convert it to an integer like this:
parseInt("000890", 10) # => 890
Note that the result here is the integer 890 not the string "890". Also note that the radix 10 is required here because the string starts with a zero.
return str.replace(/^0+(.)/, '$1'));
That is: replace maximum number of leading zeros followed by any single character (which won't be a zero), with that single character. This is necessary so as not to swallow up a single "0"
you can simply do that removing the quotation marks.
var str = 000890;
//890
var str = "000890";
//000890

Categories