remove values from a string - javascript

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

Related

How to remove the alphabet in my case using JQuery?

I wants to remove alphabet from string. In my string variable it will have the numbers with alphabet
For example
var myString = '1122D'
// I want remove the last alphabet only from the above variable
var myString = '1122Z3'
// I want remove the `Z3` from above string
var myString = '112DD2'
// I want remove the `DD2` from above string
I know how to replace specific character using .replace('',''). But in my case it is different
If the strings are always made up starting with numbers and you want to get the number up until the first alphabetical character, I'd recommend the use of parseInt() since its behaviour is exactly that it parses numeric characters in a string to a number until it encounters the first non-numeric character where it stops parsing.
var myNumber = parseInt(myString);
use this code:
myString.substr(0,myString.search('[a-zA-Z]'));
You may also do like
myString.replace(/[^\d].*/,"");
You can use regex /([\d]+).+$/g as well:
var regex = /([\d]+).+$/g;
console.log(regex.exec("1122D")[1]);
regex.lastIndex = 0;
console.log(regex.exec("1122Z3")[1]);
regex.lastIndex = 0;
console.log(regex.exec("112DD2")[1]);
Best way -
myString.slice(0, myString.indexOf(myString.match(/[a-zA-Z]/)));

How can I use JavaScript's replace function to divide a matched number by 100?

I am trying to divide a regex-matched number in string format by 100 within JavaScript's replace function:
var number = "4354543";
var result = number.replace(/(\d+)/, '$1/100');
console.log(result); -> Printing 4354543/100
The answer should be 43545.43, but instead I'm getting "4354543/100".
Is it possible to achieve this?
You can use regular expressions for this, if that's what you're really after - for instance, lets say you want to divide numbers in a larger string by 100. To do this, you have to use the function callback, which lets you manipulate the captured groups in more complex ways:
var number = "abc 4354543 xyz";
var result = number.replace(/\d+/g, function(val) {
return +val/100;
});
console.log(result); //abc 43545.43 xyz
If you know that the input strings are at least 3 digits, a simple solution is to insert a decimal separator before the last 2 digits.
var number = "4354543";
var result = number.replace(/(\d+)(\d{2})/, '$1.$2');
console.log(result);
However, using a function as the second argument to .replace, as the answer by James Thorpe does, gives you more flexibility.
I think there is some confusion in your mind about what regex can do.
In your case you really don't need regex. Just do
var number = "4354543";
console.log(number/100);
You will see what you expect, js will change string to number(don't worry)
Regexp are not suitable for mathematic operations.
Use Number javascript class.
In your case
const number = '5485454845'; // Wathever
const result = Number(number) / 100;

javascript replace not workings

I've got a problem with replace not working.
alert($('input#membership_edc').next("label").html().replace(/£/g, ""));
The value of the label after the input would be £24.00, but I want to do a math on that value then put it back with the new value. It's not removing the pound sign.
What's wrong? Thanks.
To read/modify/write use the function parameter version of .html():
$('input#membership_edc').next("label").html(function(index, old) {
var n = parseFloat(old.replace('£', '');
return n + 10;
});
would replace '£24.00' with '34'.
You need to set the value returned from the replace. Try below,
var $label = $('input#membership_edc').next("label");
$label.html($label.html().replace(/£/g, ""));
Nothing wrong. It is working here.
Are you sure your markup is fine?
The string replace function returns a new string. Strings themselves are immutable in javascript, I think. As Vega has it:
// avoid looking this up twice
var label = alert($('input#membership_edc').next("label");
// replace and assign
label.html(label.html().replace(/£/g, ""));
Edit:
To get the numerical value from the string:
var amount = alert($('input#membership_edc').next("label").html().match(/£\s*([-0-9.]+)/)[1];
This matches the numbers etc after the £ (ignoring whitespace), and uses index 1 from the array, containing the contents of the first group match (in the brackets).
" £1.45".match(/£\s*([-0-9.]+)/)[1]; // returns "1.45"
Beware that it is still a string, so you might want to do parseFloat on it.

Using JavaScript's parseInt at end of string

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.

access the last three Characters of the value in Jquery

I have a value "319CDXB" everytime i have to access last three characters of the Strring how can i do this . Usually the Length varies all the time .Everytime I need the last characters of the String using Jquery
The String .slice() method lets you use a negative index:
var str = "319CDXB".slice( -3 ); // DXB
EDIT: To expound a bit, the .slice() method for String is a method that behaves very much like its Array counterpart.
The first parameter represents the starting index, while the second is the index representing the stopping point.
Either parameter allows a negative index to be employed, as long as the range makes sense. Omitting the second parameter implies the end of the String.
Example: http://jsfiddle.net/patrick_dw/N4Z93/
var str = "abcdefg";
str.slice(0); // "abcdefg"
str.slice(2); // "cdefg"
str.slice(2,-2); // "cde"
str.slice(-2); // "fg"
str.slice(-5,-2); // "cde"
The other nice thing about .slice() is that it is widely supported in all major browsers. These two reasons make it (in my opinion) the most appealing option for obtaining a section of a String.
You can do this with regular JavaScript:
var str = "319CDXB";
var lastThree = str.substr(str.length - 3);
If you're getting it from jQuery via .val(), just use that as your str in the above code.
Simple:
str = "319CDXB"
last_three = str.substr(-3)
var str = "319CDXB";
str.substr(str.length - 3); // "DXB"

Categories