Extend a regular expression to negative number - javascript

I want to extend the following regex to negative numbers.
this.value = this.value.replace(/[^0-9\.]/g, "");
I tried adding minus sign doing something like this, (/[^-0-9.]/g, "") but this allows minus sign to be entered anywhere in the number. I want to allow only one occurance of the minus sign at the beginning of the number. Later occurances of minus should be ignored.
Please help.

Uh, replacing every non-number character makes that a bit harder - it's like "negating" the regex. What I came up with is a negative lookahead, preventing a minus - which would be matched by [^0-9.] - from beeing matched if it is in the beginning of the string (using a start anchor):
….replace(/(?!^-)[^0-9.]/g, "")

Why RegEx? How about:
var temp = parseFloat(this.value)
this.value = isNaN(temp) ? "" : temp;
This should also work:
var temp = +this.value;
this.value = isNaN(temp) ? "" : temp;

Put your dash outside of the character class:
this.value = this.value.replace(/^-?[^0-9\.]/g, "");

The regex in provided by you is faulty for the positive numbers itself as it will convert "100+200=300" to "100200300".
I suggest you try this:
someString.match(/-?[\d]+.?[\d]*/);

It is only to put the negative symbol in front of the 0
this.value = this.value.replace(/[^-0-9\.]/g, "");

Related

How to parse string value "(20)" to Integer in Javascript?

I'm working with a string "(20)". I need to convert it to an int. I read parseInt is a function which helps me to achieve that, but i don't know how.
Use string slicing and parseInt()
var str = "(20)"
str = str.slice(1, -1) // remove parenthesis
var integer = parseInt(str) // make it an integer
console.log(integer) // 20
One Line version
var integer = parseInt("(20)".slice(1, -1))
The slice method slices the string by the start and end index, start is 1, because that’s the (, end is -1, which means the last one - ), therefore the () will be stripped. Then parseInt() turns it into an integer.
Or use regex so it can work with other cases, credits to #adeithe
var integer = parseInt("(20)".match(/\d+/g))
It will match the digits and make it an integer
Read more:
slicing strings
regex
You can use regex to achieve this
var str = "(20)"
parseInt(str.match(/\d+/g).join())
Easy, use this
var number = parseInt((string).substr(2,3));
You need to extract that number first, you can use the match method and a regex \d wich means "digits". Then you can parse that number
let str = "(20)";
console.log(parseInt(str.match(/\d+/)));
Cleaner version of Hedy's
var str = "(20)";
var str_as_integer = parseInt(str.slice(1, -1))

Javascript - How to use replace() function properly

I am willing to do the following:
I have :
var distance1 = "5.5 Km";
var distance2 = "5,5 Km";
//The below works as expected and returns 5.5
var finalDistance = distance1.replace( /[^\d\.]*/g, '');
//However the below doesn't and print 55 instead
distance2.replace( /[^\d\.]*/g, '');
//I've tried the below too and it throws 5,5. But I want 5.5
distance2.replace( /[^\d\.\,]*/g, '');
First, replace all occurences of , with ., then replace non-digit characters (except .) with '':
distance2 = distance2.replace( /,/g, '.').replace(/[^\d\.]+/g, '');
where:
/,/g : matches all commas ',' that will be replaced by '.'
/[^\d\.]+ : matches any sequence of non-digit and non-dot ('.') characters that will be removed (replaced by the empty string '').
The first replace transform "5,55 KM" to "5.55 KM" then the second transform the latter to "5.55".
Note: if you only have one comma, or only interested in the first encountered one, then you could use: replace(',', '.') instead of replace(/,/g, '.').
If you are using only the float representation, you could use parseFloat instead of the second replace:
var number = parseFloat(distance2.replace(/,/g, '.'));
replace works by saying "find this string and replace with this string". The first parameter is what you want to find, the second is what to replace it with. So in your code you're replacing the , with nothing:
distance2.replace( /[^\d\.]*/g, '');
It also doesn't edit the string "in-place", so you need to assign the distance2 variable to the return value. Also, for a simple job like this you don't need to use regex. You can just input a string as the first parameter and replace will find all matches for that. This is how I would do this:
distance2 = distance2.replace(',', '.');
Further reading:
https://www.w3schools.com/jsref/jsref_replace.asp
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace
you need to reassign the replace value to the variable.
i.e.
distance2 = distance2.replace( /[^\d\.]*/g, '');

JavaScript RegEx: match all minuses that are not at start or end of string for currency input

For a currency input I want to replace all minus input that is not at the start of the string or, when it is the last character, is not preceded by a comma.
In the input event I'm already calling a replace with a simple regex for some other invalid input:
input.replace(/[^0-9\.\,\-]/g, '')
.replace('.', ',');
It would be great if I could extend this regex to also strip the invalid minuses.
Some examples of desired behavior:
50-50 -> 5050
50,00- -> 50,00
-5-0,- -> -50,-
Edit: double minus at the end or start should also be stripped.
--50,00-> -50,00
50,-- -> 50,-
I figured I could start with a positive lookahead -(?=.), but that still matches the first character.
Additionally, I found this post that pretty much does the opposite (minuses are not allowed at start and end), but that would still match the whole string. Not the sepatate minuses.
Any help would be appreciated.
Use the following approach with specific regex pattern:
var replaceHyphen = function (str) {
return str.replace(/(\d)-|(-)-/g, '$1$2');
};
console.log(replaceHyphen('50-50'));
console.log(replaceHyphen('50,00-'));
console.log(replaceHyphen('-5-0,-'));
console.log(replaceHyphen('--50,00'));
console.log(replaceHyphen('50,--'));
Is a function ok? This should do the trick:
function removeMinus(str) {
var prefix = str.startsWith("-") ? "-" : "";
var postfix = str.endsWith(",-") ? "-" : "";
return prefix + str.split("-").join("") + postfix
}
You could use word boundary \b to do that.
RegExp Boundaries
\b
Matches a word boundary. This is the position where a word character is not followed or preceeded by another word-character, such as between a letter and a space...
https://regex101.com/r/YzCiEx/1
var regex = /\b-+\b/g;
console.log("50-50".replace(regex, ''))
console.log("50,00".replace(regex, ''))
console.log("-5-0,-".replace(regex, ''))
console.log("-5------6-".replace(regex, ''))
console.log("-6--66-6,-".replace(regex, ''))

Javascript Remove all charater except leading - , one dot and digits

First of all this question is not same as
strip non-numeric characters from string or
Regex to replace everything except numbers and a decimal point
I want to convert a string with valid number like.
--1234// will be -1234
-123-123 will be -123123
12.123.3 will be 12.1233
-123.13.123 will be -123.13123
I tried those
number.replace(/[^0-9.-]/g, '') //it accepts multiple . and -
number.replace(/[^0-9.]-/g, '').replace(/(\..*)\./g, '$1');//it accepts multiple minus
I am facing Problem with leading minus sign.
How I can convert a string which will remove all characters except leading -(remove other minus),digits and only one dot(remove other dots)
Here I am sharing my solution.
Lets assume the string is a;
//this will convert a to positive integer number
b=a.replace(/[^0-9]/g, '');
//this will convert a to integer number(positive and negative)
b=a.replace(/[^0-9-]/g, '').replace(/(?!^)-/g, '');
//this will convert a to positive float number
b=a.replace(/[^0-9.]/g, '').replace(/(..*)./g, '$1');
//this will convert a to float number (positive and negative)
b=a.replace(/[^0-9.-]/g, '').replace(/(..*)./g, '$1').replace(/(?!^)-/g, '');
Update for floating number.(solves copy paste problem)
//For positive float number
b=a.replace(/[^0-9.]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.');
//For Negative float number
b=a.replace(/[^0-9.-]/g, '').replace('.', 'x').replace(/\./g,'').replace('x','.').replace(/(?!^)-/g, '');
Based on #Shaiful Islam's answer, I added one more code.
var value = number
.replace(/[^0-9.-]/g, '') // remove chars except number, hyphen, point.
.replace(/(\..*)\./g, '$1') // remove multiple points.
.replace(/(?!^)-/g, '') // remove middle hyphen.
.replace(/^0+(\d)/gm, '$1'); // remove multiple leading zeros. <-- I added this.
Result
00.434 => 0.434
Not very clean, but works!
var strings = ["-1234","-123-123","12.123.3", "-123.13.123"];
strings.forEach(function(s) {
var i = 0;
s = s.replace(/(?!^)-/g, '').replace(/\./g, function(match) {
return match === "." ? (i++ === 0 ? '.' : '') : '';
});
console.log(s);
});
In your sample data given below,
--1234
-123-123
12.123.3
-123.13.123
-(minus sign or hyphen) causes no problem because it's place is only before digits and not between digits. So this can be solved using following regex.
Regex: -(?=-)|(?<=\d)-(?=\d+(-\d+)?$) and replace with empty string.
Regex101 Demo
However, the position of .(decimal) cannot be determined. Because 123.13.123 could also mean 123.13123 and 12313.123.
Without regex, you can map over the characters this way:
// this function takes in one string and return one integer
f=s=>(
o='', // stands for (o)utput
d=m=p=0, // flags for: (d)igit, (m)inus, (p)oint
[...s].map(x=> // for each (x)char in (s)tring
x>='0'&x<='9'? // if is number
o+=x // add to `o`
:x=='-'? // else if is minus
m||(p=0,m=o=x) // only if is the first, reset: o='-';
:x=='.'? // else if is point
p||(p=o+=x) // add only if is the first point after the first minus
:0), // else do nothing
+o // return parseInt(output);
);
['--1234','-123-123','12.123.3','-123.13.123'].forEach(
x=>document.body.innerHTML+='<pre>f(\''+x+'\') -> '+f(x)+'</pre>')
Hope it helps.
My solution:
number.replace(/[^\d|.-]/g, '') //removes all character except of digits, dot and hypen
.replace(/(?!^)-/g, '') //removes every hypen except of first position
.replace(/(\.){2,}/g, '$1') //removes every multiplied dot
It should then formatted to the proper locale setting using Intl.NumberFormat.

Add colon (:) after every 2nd character using Javascript

I have a string and want to add a colon after every 2nd character (but not after the last set), eg:
12345678
becomes
12:34:56:78
I've been using .replace(), eg:
mystring = mystring.replace(/(.{2})/g, NOT SURE WHAT GOES HERE)
but none of the regex for : I've used work and I havent been able to find anything useful on Google.
Can anyone point me in the right direction?
Without the need to remove any trailing colons:
mystring = mystring.replace(/..\B/g, '$&:')
\B matches a zero-width non-word boundary; in other words, when it hits the end of the string, it won't match (as that is considered to be a word boundary) and therefore won't perform the replacement (hence no trailing colon, either).
$& contains the matched substring (so you don't need to use a capture group).
mystring = mystring.replace(/(..)/g, '$1:').slice(0,-1)
This is what comes to mind immediately. I just strip off the final character to get rid of the colon at the end.
If you want to use this for odd length strings as well, you just need to make the second character optional. Like so:
mystring = mystring.replace(/(..?)/g, '$1:').slice(0,-1)
If you're looking for approach other than RegEx, try this:
var str = '12345678';
var output = '';
for(var i = 0; i < str.length; i++) {
output += str.charAt(i);
if(i % 2 == 1 && i > 0) {
output += ':';
}
}
alert(output.substring(0, output.length - 1));
Working JSFiddle
A somewhat different approach without regex could be using Array.prototype.reduce:
Array.prototype.reduce.call('12345678', function(acc, item, index){
return acc += index && index % 2 === 0 ? ':' + item : item;
}, ''); //12:34:56:78
mystring = mytring.replace(/(.{2})/g, '\:$1').slice(1)
try this
Easy, just match every group of up-to 2 characters and join the array with ':'
mystring.match(/.{1,2}/g).join(':')
var mystring = '12345678';
document.write(mystring.match(/.{1,2}/g).join(':'))
no string slicing / trimming required.
It's easier if you tweak what you're searching for to avoid an end-of-line colon(using negative lookahead regex)
mystring = mystring.replace(/(.{2})(?!$)/g, '\$1:');
mystring = mystring.replace(/(.{2})/g, '$1\:')
Give that a try
I like my approach the best :)
function colonizer(strIn){
var rebuiltString = '';
strIn.split('').forEach(function(ltr, i){
(i % 2) ? rebuiltString += ltr + ':' : rebuiltString += ltr;
});
return rebuiltString;
}
alert(colonizer('Nicholas Abrams'));
Here is a demo
http://codepen.io/anon/pen/BjjNJj

Categories