Javascript append colon to numbers of unknown length? - javascript

I have a number let's say
305060
And I want to put a : at the -2 and -4 spot so I end up with
30:50:60
And if I entered 5006070 I would end up with 500:60:70
I can't seem to figure out how to do this.

Use this code:
var number = 123456789;
var formatted = number.toString().replace(/^(\d+)(\d{2})(\d{2})/, '$1:$2:$3');
alert(formatted);
Demo: http://jsfiddle.net/U4J6n/
If number is a string, you can remove the .toString() method from the code.

You could use a regex that catches the two last groups of two numbers
/(\d{2})(\d{2})$/
so it's
var x = 305060;
x = x.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 30:50:60
var x2 = 5006070;
x2 = x2.toString().replace(/(\d{2})(\d{2})$/, ":$1:$2"); // 500:60:70
FIDDLE

Lets suppose n is the length of the string, first you want to take the number from 0 to n-4 then n-4 to n-2 and finally n-2 to n, so simply use one of substring or slice to get the solution.
If you want to use substring then it would be
var num="305060";
var length=num.length;
var ans=num.substring(0,length-4)+":"+num.substring(length-4,length-2)+":"+num.substring(length-2,length);
alert(ans);
If you want to use slice then
var num="305060";
var length=num.length;
var ans=num.slice(0,length-4)+":"+num.slice(length-4,length-2)+":"+num.slice(length-2,length);
alert(ans);
substr is another function in javascript which will help you to get the solution
var num="305060";
var length=num.length;
var ans=num.substr(0,length-4)+":"+num.substr(length-4,2)+":"+num.substr(length-2,2);
alert(ans);

You can use String.prototype.slice
Javascript
var x = 305060,
y = x.toString(),
z = [y.slice(0, -4), y.slice(-4, -2), y.slice(-2)].join(':');
console.log(z);
Output
30:50:60
On jsFiddle

Related

How to turn all integers in an array into a single number? [duplicate]

How do I join this array to give me expected output in as few steps as possible?
var x = [31,31,3,1]
//expected output: x = 313131;
Use array join method.Join joins the elements of an array into a string, and returns the string. The default separator is comma (,). Here the separator should be an empty string.
var x = [31,31,3,1].join("");
EDIT: To get the result as numeric
const x = +[31,31,3,1].join("");
or
const x = Number([31,31,3,1].join(""));
Javascript join() will give you the expected output as string. If you want it as a number, do this:
var x = [31,31,3,1];
var xAsString = x.join(''); // Results in a string
var xAsNumber = Number(x.join('')); // Results in a number, you can also use +(x.join(''))
I can't think of anything other than
+Function.call.apply(String.prototype.concat, x)
or, if you insist
+''.concat.apply('', x)
In ES6:
+''.concat(...x)
Using reduce:
+x.reduce((a, b) => a + b, '');
Or if you prefer
x.reduce(Function.call.bind(String.prototype.concat), '')
Another idea is to manipulate the array as a string, always a good approach.
+String.prototype.replace.call(x, /,/g, '')
There may be other ways. Perhaps a Google search on "join array javascript" would turn up some obscure function which joins elements of an array.
Your question asks for a number, most of the answers above are going to give you a string. You want something like this.
const number = Number([31,31,3,1].join(""));
Try join() as follows
var x = [31,31,3,1]
var y = x.join('');
alert(y);
Try below.
var x = [31,31,3,1]
var teststring = x.join("");
This will work
var x = [31,31,3,1];
var result = x.join("");

Dynamic regex pattern in JavaScript

I have some code that matches a certain number of digits after a decimal. Currently, I have the following:
var input = getValueFromUser();
var count = getCount();
var x = Number(input.toString().match(/^\d+(?:\.\d{0,1})?/));
alert(x);
This approach always gets the first digit after the decimal. However, I want to replace the 1 in the regex with the value in count. How do I do that? I tried the following:
var pattern = '/^\d+(?:\.\d{0,' + count + '})?/';
var x = Number(input.toString().match(pattern));
However, now, I always get 0 for x.
You have to use Regexp object if you want to use dynamically built patterns:
var re = new RegExp('^\\d+(?:\\.\\d{0,' + count + '})?');
This will help you.
var pattern = '^\\d+(?:\\.\\d{0,' + '5' + '})?',
reg=new RegExp(pattern),
x = Number(input.toString().match(reg));
mask: new RegExp(`^[a-zA-Z0-9]{0,${maxLength}}$`)
its work for me
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)

Parsing a String looking characters

I am trying to extract the numbers of this string: "ax(341);ay(20);az(3131);"
I think that I can do it how this:
var ax = data.split('(');
var ax2 = ax[1].split(')');
ax2[0] has "341"
Now If I can repeat this but starting in the next indexOf to take the second number.
I think that it's a bad practice, so I ask you If you have a better idea.
Thanks in advance
Use a regular expression:
var str = "ax(-341);ay(20);az(3131);"
var regex = /(-?\d+)/g
var match = str.match(regex);
console.log(match); // ["-341", "20", "3131"]
Now you can just access the numbers in the array as normal.
DEMO
You can use regex to extract all numbers from this.
var data = "ax(341);ay(20);az(3131);";
var ax = data.match(/\d+/g);
Here ax is now ["341", "20", "3131"]
Note that ax contains numbers as string. To convert them to number, use following
ax2 = ax.map( function(x){ return parseInt(x); } )
EDIT: You can alternatively use Number as function to map in the line above. It'll look like,
ax2 = ax.map( Number )
After this ax2 contains all the integers in the original string.
You could use a regular expression, eg:
var string = 'ax(341);ay(20);az(3131);';
var pattern = /([0-9]{1,})/g;
var result = string.match(pattern);
console.log(result);
// ["341", "20", "3131"]
http://regex101.com/r/zE9pS7/1

How can I convert this into a integer in Javascript?

I asked a similar question yesterday .. If I have for example 0-9999 , how can I turn this into 09999 , basically removing the - and make it an integer in javascript ?
var = 0-9999
turn that into 9999 integer
or var = 2-9999 , turn that into 29999
Thanks a bunch
This should do the trick:
num = num.replace(/[^0-9]+/g, '') * 1;
It'll strip out any non-numeric characters and convert the variable into an integer. Here's a jsFiddle demonstration for you.
The most obvious and basic of solutions would be:
var s = "1-2345";
var t = s.replace("-","");
var i = parseInt(t,10);
But that's making a lot of assumptions and ignoring any errors.
Try this:
var i = '0-9999';
var int = Number(i.replace('-', ''));
window.alert(int);
Note in Firefox, parseInt() won't work with leading zeros unless you pass in a radix (this appears to be a bug):
var int = parseInt(i.replace('-', ''), 10);
Fiddler
Remember that
var x = 2-9999
is the same as
var x = -9997
because the dash is seen as a subtraction symbol unless you use quotation marks (Single or double, doesn't matter).
So, assuming that you properly quote the text, you can use the following function to always pull out a character that is in any given spot of the text (Using a zero-based index).
function extractChar(myString,locationOfChar){
var y = myString.substring(0,locationOfChar-1)
var z = myString.substring(locationOfChar+1)
var s = y.concat(z)
var i = parseInt(s,10)
return i
}
therefore
var i = extractChar("2-9999",1)
Will be the same as
var i = 29999

adding numbers from array?

i have:
var str="100px";
var number = str.split("px");
number = number[0];
var km = "100px";
var numberk = km.split("px");
numberk = numberk[0];
var gim = numberk+100;
var kim = number+100;
var fim = number+numberk;
document.write(gim+'<br>'+kim+'<br>'+jim+'<br>');
i would be thankfull if someone could me answere why the result are added like string rather than nummerical number in javascript i have used the isNaN(); function which shows this as a legal number. So how can this problem be solved.
thanks.
You could use the parseInt function in order to convert the string returned when spliting into integer:
number = parseInt(number[0], 10);
numberk = parseInt(numberk[0], 10);
Now the 2 variables are integers and you could perform integer operations on them.
You need to put parseInt() around each number before you use it. In fact, you could do this without removing the "px".
gim = parseInt(km) + 100;
simplest way to do this, you don't need to use split.
var str="150px";
var str1 = (parseInt(str)+100)+"px";
alert(str1);
OUTPUT:
200px
fiddle : http://jsfiddle.net/Kk3HK/1/
use parseInt()
var number = parseInt(str, 10);
var numberk = parseInt(km, 10);
Use parseInt to convert the string to a number.
var str = "100px";
var number = parseInt(str, 10);
parseInt stops when it finds the first non-number character, so you don't even need to remove the "px".
Wrap the numbers in parseInt().

Categories