jQuery after divide number add symbol - javascript

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.

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));

How to get the ID from this URL?

I need a way to get the ID ( 153752044713801 in this case ) of this page:
https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801
I tried this code but doen't work:
var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;
if(re1.exec(fburl)){
str = re1.exec(fburl)[3];
pagefb = str.substr(str.lastIndexOf("-") + 1);
alert('ok');
}
try:
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);
Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)
(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)
this works for me
fburl.split('/')[fburl.split('/').length-1]
You can split the string using .split("/"). More information is availible on MDN
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets).
The parts[parts.length - 1] will get the last item in the array parts
Demo below (Don't worry about the document..., they just print out data):
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
// If first digit is ?
if (myFacebookId[0] == '?') {
// Set myFacebookId to the second from last part
myFacebookId = parts[parts.length - 2]
}
document.write('MyFacebookId: ' + myFacebookId)

Javascript slice from reverse

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

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>");
}

how to parse string to int in javascript

i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string
var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.
You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example
var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);
var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}
Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);
This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");
Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121
First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22
javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string

Categories

Resources