How to add digit before first character of string in javascript? - javascript

I have a string, and I need to get its first character. if that character is alphabetic (between A to Z or a to z)then i want add any digit in-front of that character
var x = 'somestring'
alert(x.charAt(0));
in above string first character has alphabet then i need to attach any digit (0 to 9) before string
4somestring
How can I fix my code?

if (/[a-zA-Z]/.test(x.charAt(0))) {
x = (Math.floor(Math.random() * 10)) + x;
}
Simply use regexes, the test method, and Math.random.
You could also use an anchor so you don't have to call charAt:
if (/^[a-zA-Z]/.test(x)) {
Here is a fiddle.

var x = 'somestring';
if (! /^\d+$/.test(x[0]))
x = 5 + x; // or some other number

Related

Remove last dots from characters in jquery

How to remove only the last dots in characters in jquery?
Example:
1..
1.2.
Expected result:
1
1.2
My code:
var maskedNumber = $(this).find('input.CategoryData');
var maskedNumberValue = $(maskedNumber).val().replace(/[^0-9.]/g, '').replace('.', 'x').replace('x', '.').replace(/[^\d.-]/g, '');
console.log(maskedNumberValue.slice(0, -1))
How do I solve this problem? Thanks
You can use regex replace for that:
function removeLastDot(value) {
return value.replace(/\.*$/, '')
}
console.log(removeLastDot('1..'))
console.log(removeLastDot('1.2.'))
In the example I use \.*$ regex:
$ - means that I want replace at the end of string
\.* - means that I want to match any number for . symbol (it is escaped cause . is special symbol in regex)
You can traverse the string with forEach and store the last index of any number in a variable. Then slice up to that variable.
let lastDigitIndex = 0;
for (let i = 0; i < str.length; i++) {
let c = str[i];
if (c >= '0' && c <= '9') lastDigitIndex = i;
};
console.log(str.slice(0, lastDigitIndex-1));
This will be an optimal solution.
maybe this can help.
var t = "1...";
while (t.substr(t.length - 1, 1) == ".") {
t = t.substr(0,t.length - 1);
}
import re
s = '1.4....'
# reverse the string
rev_s = s[::-1]
# find the first digit in the reversed string
if first_digit := re.search(r"\d", rev_s):
first_digit = first_digit.start()
# cut off extra dots from the start of the reversed string
s = rev_s[first_digit:]
# reverse the reversed string back and print the normalized string
print(s[::-1])
1.4
Add replace(/\.*$/g, '') to match one or more dots at the end of the string.
So your code would be like this:
var maskedNumberValue = $(maskedNumber).val().replace(/[^0-9.]/g, '').replace('.', 'x').replace('x', '.').replace(/[^\d.-]/g, '').replace(/\.*$/g, '');

Javascript add count to a number with comma

So I have this
var str=document.getElementById('elem').innerHTML;
str=parseInt(str)+1;
<span id="elem">1,500</span>
and I can't get it to take the entire number and add one (+1) to the number without taking comma off. Can you suggest something?
Remove the commas by replacing them with an empty string, then you can parse the string.
Remember the second parameter in the parseInt method that specifies the base, so that it doesn't use base 8 for zero padded values.
var num = parseInt(str.replace(/,/g, ''), 10) + 1;
If you want to put the changed number back formatted with commas, you can use:
var s = num.toString();
for (var i = s.length - 3; i > 0; i -= 3) {
s = s.substr(0, i) + ',' + s.substr(i);
}
document.getElementById('elem').innerHTML = s;

Replace the last and first integers of a string

I have a string like this : var input = "/first_part/5/another_part/3/last_part"
I want to replace the last occurence of integers (3 in my string), then the first occurence (5).
I tried this: input .replace(/\d+/, 3); which replace all occurences. But how to only target the last / first one.
Thanks in advance.
This will replace the first and last single digit in the input string with 3
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$13$23$3");
Here's a reFiddle link that demos this: http://refiddle.com/1am9
More readable:
var replacement = '3';
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$1" + replacement + "$2" + replacement + "$3");
or input.replace(/^(.*?)\d(.*)\d(.*)$/, ["$1", "$2", "$3"].join(replacement)); if that's your thing.
You can use this negative lookahead based regex:
var input = "/first_part/5/another_part/3/last_part";
// replace first number
var r = input.replace(/\d+/, '9').replace(/\d+(?=\D*$)/, '7');
//=> /first_part/9/another_part/7/last_part
Here \d+(?=\D*$) means match 1 or more digits that are followed by all non-digits till end of line.
Here is a pretty rigid approach to your problem, you might want to adapt it to your needs, but it shows one way you can get things done.
// input string
var string = "/first_part/5/another_part/3/last_part";
//match all the parts of the string
var m = string.match(/^(\D+)(\d+)+(\D+)(\d+)(.+)/);
// ["/first_part/5/another_part/3/last_part", "/first_part/", "5", "/another_part/", "3", "/last_part"]
// single out your numbers
var n1 = parseInt(m[2], 10);
var n2 = parseInt(m[4], 10);
// do any operations you want on them
n1 *= 2;
n2 *= 2;
// put the string back together
var output = m[1] + n1 + m[3] + n2 + m[5];
// /first_part/10/another_part/6/last_part

numeric variables in JS

For a variable x=5, how do I know it is number five or the character '5'?
Btw, in JS, do characters follow the ASCII table? Then can I manipulate a character variable. For example, if variable x is character a, can I do x=x+1 to make it character b?
To see if x is the number 5, as opposed to the string "5", you can use the identity operator:
if (x === 5) {
}
Identity will not do any implicit conversions; it will return true only if both operands are equal without any conversions.
For example, if variable x is character a, can I do x=x+1 to make it
character b?
No. x = x + 1 will convert 1 to a string, perform string concatenation and return "a1"
You can use
typeof x;
which returns a string describing the type of the variable, like number, string or object.
To get the character code of a character, use charCodeAt:
var mystring = 'a';
mystring.charCodeAt(0);
And to get a character from an augmented char code, use String.fromCharCode :
var nextLetter = String.fromCharCode( mystring.charCodeAt(0) + 1 ); // returns "b"
This creates a new string from the incremented char code from the first character in mystring.
Just get the type of the variable:
console.log(typeof '5'); // Returns 'string';
console.log(typeof 5); // Returns 'number';
As for your second question, no, it doesn't work:
console.log('b' + 1); // Returns 'b1'
To check if a variable is a number:
if (typeof x == 'number')
// x is a number
Doing this x = x + 1 when x = b, would result in the string 'a1';
If your var x is not an integer, this is the best way to change it to integer..
To change the x to integer
x = parseInt(x);
You can how add any value to the x, example:
x = x + 2;
Since we have changed the x to integer, we can now identify if this is equal to 5
if(x == 5){
//Your Codes Here
}

Remove/ truncate leading zeros by javascript/jquery

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
I would use the Number() function:
var str = "00001";
str = Number(str).toString();
>> "1"
Or I would multiply my string by 1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Maybe a little late, but I want to add my 2 cents.
if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.
e.g.
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.
and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
hope it helps somebody
Since you said "any string", I'm assuming this is a string you want to handle, too.
"00012 34 0000432 0035"
So, regex is the way to go:
var trimmed = s.replace(/\b0+/g, "");
And this will prevent loss of a "000000" value.
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
You can see a working example here
parseInt(value) or parseFloat(value)
This will work nicely.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
1. The most explicit is to use parseInt():
parseInt(number, 10)
2. Another way is to use the + unary operator:
+number
3. You can also go the regular expression route, like this:
number.replace(/^0+/, '')
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
You should use the "radix" parameter of the "parseInt" function :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal
parseInt('015') => 0
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
const number = '0000007457841';
console.log(+number) //7457841;
OR number.replace(/^0+/, '')
Regex solution from Guffa, but leaving at least one character
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.
And I ended up doing so:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Use "Math.abs"
eg: Math.abs(003) = 3;
console.log(Math.abs(003))

Categories

Resources