Javascript slice from reverse - javascript

I want to slice the javascript variable in the given condition.
The condition is if the variable is of length 12 it should slice as 2,6,4 and if it is of length 11 it should slice as 2,5,4. How can i slice this.
Here is what i have tried.
Code :
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);
How can i make the length checking condition and slice according to my given condition ?

You can make the middle slice conditional:
var midEnd = phone_no.length == 11? 7 : 8;
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,midEnd)+"-"+phone_no.slice(midEnd);
If you don't supply a second parameter, it will slice to the end. Though for greater browser compatibility I'd use substr instead:
var new_no = '(' + phone_no.substr(0,2) + ')-' +
phone_no.substr(2,midEnd) +
'-' + phone_no.substr(midEnd);

function preparePhoneNo(num) {
return '(' + num.slice(0, 2) + ')-' + num.slice(2, -4) + '-' + num.slice(-4);
}
var phone_no = "123465789012";
var new_no = preparePhoneNo(phone_no);

Here is my take, I would use substr
var phone_no = '12345678901';
var midGroup = phone_no.length == 11 ? 5 : 6;
var new_no = "("+phone_no.substr(0,2)+")-"+phone_no.substr(2,midGroup)+"-"+phone_no.substr(midGroup + 2);
alert(new_no);

You can simply use .length to check the length of the number and then two simple conditions will do the trick:
var phone_no = "123456789878";
if(phone_no.length === 11)
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,7)+"-"+phone_no.slice(7,11);
else if(phone_no.length === 12)
var new_no = "("+phone_no.slice(0,2)+")-"+phone_no.slice(2,8)+"-"+phone_no.slice(8,12);
else
alert('Invalid Number');
See the DEMO here

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

jQuery after divide number add symbol

I have text at the cell and want to:
if last number is not equal zero then number / 10 and add symbol "+", so ex. +15.7
if last number is equal 0 then number / 10. Result it ex. 15 and add symbol "+" and ".0", so ex. +15.0
<td id='testid'>157</td>
I create javascript and do not how add auxiliary symbols. This solution do not work correctly.
<script>
$(document).ready(function(){
var predpona = '+';
var pom = $('#testid').text();
var lastChar = pom.slice(-1);
var newPom;
if (lastChar != '0') {newPom = (pom/10) } else {newPom = (pom/10).prepend(predpona); }
$('#testid').text(newPom);
});
</script>
Thanks very much.
If the decimal part is always after the second character here you have an alternative
var predpona = '+';
var pom = $('#testid').text();
var index = 2;
var newPom = predpona + [pom.slice(0, index), '.', pom.slice(index)].join('');
Use parseint(), it converts the value into integer form.
$(document).ready(function(){
var predpona = '+',
pom = $('#testid').text(),
lastChar = pom.slice(-1),
newPom = parseint(pom) / 10;
if (lastChar == '0')
newPom += '.0';
$('#testid').text('+' + newPom);
});
If you always want one decimal place and the line preceded with a "+" symbol try this.
$(document).ready(function () {
var predpona = '+';
var pom = $('#testid').text();
var lastChar = pom.slice(-1);
var newPom = predpona + (pom / 10).toFixed(1);
$('#testid').text(newPom);
});
Here is a fiddle to mess around with.

Wrap each digitand prepend zeros up to X digits

Is there a possibility to wrap each character in Javascript and prepend zero's if its less then X digits?
What i get/have:
var votes = 2;
//or
var votes = 123;
//or
var votes = 4321;
what it should to look like:
<span>0</span><span>0</span><span>0</span><span>2</span>
//or
<span>0</span><span>1</span><span>2</span><span>3</span>
//or
<span>4</span><span>3</span><span>2</span><span>1</span>
so the result should be a number with four digits.
here's a tricky version:
var votes = 123;
("0000" + votes).slice(-4); /* 0123 */
thus, to wrap each digit in a <span> you could fetch each digit with $.map and wrap it into its own element, like in this example fiddle: http://jsfiddle.net/cZAWj/
var votes = 973;
$.map(("0000" + votes).slice(-4), function(digit) {
$('<span/>', { text : digit }).appendTo($('body'));
});
Firstly, make it look like a string and pad it...
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Then you can iterate over it and add a span around each number. Then write the markup out as the .html of the parent element.
Well one way to do it would be to convert the number to a string and pre-append 0 until we reach the desired length.
So if you want X digits:
var strNb = "" + nb;
while (strNb.length < X){
strNb = "0" + strNb
}
function formatNumber(d, x) {
var l = String(d).length;
return (l<x?(Array(x-l).join('0') + d):String(d)).replace(/\d/g,"<span>$&</span>");
}

convert js number to xxx xxx xxx ,xx?

I have an number I want convert its format to xxx xxx xxx,xx(will use for display in html page)
Example
1069.83
to
1 069,83
OR something like this
13761000.00
to
13 761 000,00
In JavaScript are the build-in function or the ways to do this?
If this is your data pattern you can enhance this function: ( see it here : http://jsfiddle.net/DSJuL/1/ )
var number = 13761000.00;
alert(formatNum(number));
function formatNum(number)
{
var newNum = "";
var oldNumStr = number + "";
var done = 0;
var parts = oldNumStr.split(".");
var newPart1 = "";
var newPart2 = parts[1];
for(var j= parts[0].length -1 ;j >= 0;j--)
{
newNum = parts[0][j] + newNum;
done++;
if((done%3) == 0)
newNum = " " + newNum;
}
newNum = (newPart2)? (newNum + "," + newPart2) : newNum + ",00" ;
return newNum;
}
If using jQuery is an option you can check the globalization plugin. It supports number formatting nicely. Check this out.
If you can't use jQuery - check this.

Categories

Resources