Remove all numbers including floats from string with Javascript - javascript

I have these strings with numbers
"$12.3"
"12,3 SEK"
"12 pounds"
In all the occurrences i need to remove the number, float or not, and just keep the rest of the string.
"$"
"SEK"
"pounds"
I found several posts that are similar to my question, like this one:
Removing Numbers from a String using Javascript
Where something like this is suggested in a comment:
"12.3 USD".replace(/\d+([,.]\d+)?/g)
But that only returns (with the Chrome dev console):
"undefined USD"

That's because you aren't telling it what to replace those values with. Try
"12.3 USD".replace(/\d+([,.]\d+)?/g, '')
// replace with an empty string ---^
It looks like you also want to remove any whitespace coming after the numbers so you could modify your regex a bit to do that.
let result = "12.3 USD".replace(/\d+([,.]\d+)?\s*/g, '');
// remove whitespace ---^
console.log(result);

Related

Cant Find the position of a letter in the string

I got a string Like this
var test = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Actually I can't find the position of "t" in this string. don't know why,
I used indexOf, tried to convert this into string object, but all got in vain
note : Please use the exact string given in the question,
Thanks,
These are non-standard characters, so to search for the "t" in in, you have to actually copy and paste the t from your string.
>> test.indexOf("t")
>> 29
For demonstration:
"t".charCodeAt()
116 // ASCII code for lowercase t
"t".charCodeAt()
65364 // Something non-standard
You can't find because it's not 't' you are trying to find. Take a look at "t".charCodeAt(0) which returns 65364 and "t".charCodeAt(0) which yields 116. Those are different characters.
Use String.prototype.indexOf() which will return the index within the calling String object of the first occurrence of the specified value.
Please note that t in your string is a "non-standard character" and won't be found by indexOf() if you use a "standard character ".
More information here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
var test = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(test.indexOf("t"));

How to check if a string contains a number in JavaScript?

I don't get how hard it is to discern a string containing a number from other strings in JavaScript.
Number('') evaluates to 0, while '' is definitely not a number for humans.
parseFloat enforces numbers, but allow them to be tailed by abitrary text.
isNaN evaluates to false for whitespace strings.
So what is the programatically function for checking if a string is a number according to a simple and sane definition what a number is?
By using below function we can test whether a javascript string contains a number or not. In above function inplace of t, we need to pass our javascript string as a parameter, then the function will return either true or false
function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}
If you want something a little more complex regarding format, you could use regex, something like this:
var pattern = /^(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
Demo
I created this regex while answering a different question awhile back (see here). This will check that it is a number with atleast one character, cannot start with 0 unless it is 0 (or 0.[othernumbers]). Cannot have decimal unless there are digits after the decimal, may or may not have commas.. but if it does it makes sure they are 3 digits apart, etc. Could also add a -? at the beginning if you want to allow negative numbers... something like:
/^(-)?(0|[1-9][0-9]{0,2}(?:(,[0-9]{3})*|[0-9]*))(\.[0-9]+){0,1}$/;
There's this simple solution :
var ok = parseFloat(s)==s;
If you need to consider "2 " as not a number, then you might use this one :
var ok = !!(+s==s && s.length && s.trim()==s);
You can always do:
function isNumber(n)
{
if (n.trim().length === 0)
return false;
return !isNaN(n);
}
Let's try
""+(+n)===n
which enforces a very rigid canonical way of the number.
However, such number strings can be created by var n=''+some_number by JS reliable.
So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.
No need to panic just use this snippet if name String Contains only numbers or text.
try below.
var pattern = /^([^0-9]*)$/;
if(!YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Charectors.}
if(YourNiceVariable.value.match(pattern)) {//it happen while Name Contains only Numbers.}
This might be insane depending on the length of your string, but you could split it into an array of individual characters and then test each character with isNaN to determine if it's a number or not.
A very short, wrong but correctable answer was just deleted. I just could comment it, besides it was very cool! So here the corrected term again:
n!=='' && +n==n'
seems good. The first term eliminates the empty string case, the second one enforces the string interpretataion of a number created by numeric interpretation of the string to match the string. As the string is not empty, any tolerated character like whitespaces are removed, so we check if they were present.

Split by regex yield "undefined"

I have a code which extract query string parameters :
So ( for example) if the window url is :
....&a=1&.....
--The code first using split on & and then do split on the =
however , sometimes we use base64 values , which can have extra finals ='s (padding).
And here is where my code is messed up.
the result is N4JOJ7yZTi5urACYrKW5QQ and it should be N4JOJ7yZTi5urACYrKW5QQ==
So I enhance my regex to :
search = such that after it -> ( there is no end OR there is no [=])
'a=N4JOJ7yZTi5urACYrKW5QQ=='.split(/\=(?!($|=))/)
it does work. ( you can run it on console)
but the result is ["a", undefined, "N4JOJ7yZTi5urACYrKW5QQ=="]
Why am I getting undefined
How can i cure my regex for yielding only ["a", "N4JOJ7yZTi5urACYrKW5QQ=="]
p.s.
I know i can replace all the finals ='s to something temporary and then replace it back
but this tag is tagged as regex. So im looking a way to fix my regex.
This happens because you have additional match ($|=). You can exclude it from matching with ?::
"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!(?:$|=))/);
However, you can always flatten that match and remove extra block:
"a=N4JOJ7yZTi5urACYrKW5QQ==".split(/=(?!$|=)/);
The url needs to be encoded
'a=N4JOJ7yZTi5urACYrKW5QQ=='
should be
'a=N4JOJ7yZTi5urACYrKW5QQ%3D%3D'
Look into encodeURIComponent()
And if you want to use a reg expression to get the key from the value
> "abc=fooo".match(/([^=]+)=?(.*)?/);
["abc=fooo", "abc", "fooo"]
why must you use split? a regex match with two captures, like /^(.+)=(.+)$/ would seem more obvious.

What does this JS do?

var passwordArray = pwd.replace(/\s+/g, '').split(/\s*/);
I found the above line of code is a rather poorly documented JavaScript file, and I don't know exactly what it does. I think it splits a string into an array of characters, similar to PHP's str_split. Am I correct, and if so, is there a better way of doing this?
it replaces any spaces from the password and then it splits the password into an array of characters.
It is a bit redundant to convert a string into an array of characters,because you can already access the characters of a string through brackets(.. not in older IE :( ) or through the string method "charAt" :
var a = "abcdefg";
alert(a[3]);//"d"
alert(a.charAt(1));//"b"
It does the same as: pwd.split(/\s*/).
pwd.replace(/\s+/g, '').split(/\s*/) removes all whitespace (tab, space, lfcr etc.) and split the remainder (the string that is returned from the replace operation) into an array of characters. The split(/\s*/) portion is strange and obsolete, because there shouldn't be any whitespace (\s) left in pwd.
Hence pwd.split(/\s*/) should be sufficient. So:
'hello cruel\nworld\t how are you?'.split(/\s*/)
// prints in alert: h,e,l,l,o,c,r,u,e,l,w,o,r,l,d,h,o,w,a,r,e,y,o,u,?
as will
'hello cruel\nworld\t how are you?'.replace(/\s+/g, '').split(/\s*/)
The replace portion is removing all white space from the password. The \\s+ atom matches non-zero length white spcace. The 'g' portion matches all instances of the white space and they are all replaced with an empty string.

Javascript Regex: replacing the last dot for a comma

I have the following code:
var x = "100.007"
x = String(parseFloat(x).toFixed(2));
return x
=> 100.01
This works awesomely just how I want it to work. I just want a tiny addition, which is something like:
var x = "100,007"
x.replace(",", ".")
x.replace
x = String(parseFloat(x).toFixed(2));
x.replace(".", ",")
return x
=> 100,01
However, this code will replace the first occurrence of the ",", where I want to catch the last one. Any help would be appreciated.
You can do it with a regular expression:
x = x.replace(/,([^,]*)$/, ".$1");
That regular expression matches a comma followed by any amount of text not including a comma. The replacement string is just a period followed by whatever it was that came after the original last comma. Other commas preceding it in the string won't be affected.
Now, if you're really converting numbers formatted in "European style" (for lack of a better term), you're also going to need to worry about the "." characters in places where a "U.S. style" number would have commas. I think you would probably just want to get rid of them:
x = x.replace(/\./g, '');
When you use the ".replace()" function on a string, you should understand that it returns the modified string. It does not modify the original string, however, so a statement like:
x.replace(/something/, "something else");
has no effect on the value of "x".
You can use a regexp. You want to replace the last ',', so the basic idea is to replace the ',' for which there's no ',' after.
x.replace(/,([^,]*)$/, ".$1");
Will return what you want :-).
You could do it using the lastIndexOf() function to find the last occurrence of the , and replace it.
The alternative is to use a regular expression with the end of line marker:
myOldString.replace(/,([^,]*)$/, ".$1");
You can use lastIndexOf to find the last occurence of ,. Then you can use slice to put the part before and after the , together with a . inbetween.
You don't need to worry about whether or not it's the last ".", because there is only one. JavaScript doesn't store numbers internally with comma or dot-delimited sets.

Categories