Checking if numbers are valid from inputs then adding them - javascript

Not sure there's a way to do this but what's happening is that I am adding 2 values from inputs then displaying them in a label $totalRetailAmountField. However, sometimes if you put dashes in either of the numbers, it's throwing off the final number (even when using a regex to strip out dashes, commas, etc). Is there a way to first check the numbers, then add them if they are? Thanks
function calcTotalRetailVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
if (!isNaN(result)) {
$totalRetailAmountField.text('$' + result.toFixed(2));
}
}
calcTotalRetailVal();
$oneTimeCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});

In your pattern (,|[^\d.-]+)+ you use an alternation to match either a comma, or a negated character class that match any character that is NOT listed due to using the ^ at the start like [^\d.-]
That means you are not removing digits, dots but you are also not removing dashes.
regex101 demo
Depending on what you want to replace with an empty string, you could use a single character class and list what you would like to replace like matching a comma, dash or whitespace char [,\s-], or use \D+ to match all non digits.
For example num1.replace(/[,\s-]+/g, '') or num1.replace(/\D+/g, '')

Not sure if I understood the question right but if your intent is to get rid of all possible dashes in a string, using the following regExp as the first parameter of your replace method should be fine I suppose.
/-/g
So your code would go from
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
to
var result = parseFloat(num1.replace(/-/g, '')) + parseFloat(num2.replace(/-/g, ''));
In fact the regExp you're using does match anything that's not a digit, the . character or a dash.

Related

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

Get all characters not matching the Reg expression Pattern in Javascript

I have below requirement where a entered text must match any of below allowed character list and get all characters not matching the reg exp pattern.
0-9
A-Z,a-z
And special characters like:
space,.#,-_&()'/*=:;
carriage return
end of line
The regular expression which I could construct is as below
/[^a-zA-Z0-9\ \.#\,\r\n*=:;\-_\&()\'\/]/g
For an given example, say input='123.#&-_()/*=:/\';#$%^"~!?[]av'. The invalid characters are '#$%^"~!?[]'.
Below is the approach I followed to get the not matched characters.
1) Construct the negation of allowed reg expn pattern like below.
/^([a-zA-Z0-9\ \.#\,\r\n*=:;\-_\&()\'\/])/g (please correct if this reg exp is right?)
2) Use replace function to get all characters
var nomatch = '';
for (var index = 0; index < input.length; index++) {
nomatch += input[index].replace(/^([a-zA-Z0-9\ \.#\,\r\n*=:;\-_\&()\'\/])/g, '');
}
so nomatch='#$%^"~!?[]' // finally
But here the replace function always returns a single not matched character. so using a loop to get all. If the input is of 100 characters then it loops 100 times and is unnecessary.
Is there any better approach get all characters not matching reg exp pattern in below lines.
A better regular expression to get not allowed characters(than the negation of reg exp I have used above)?
Avoid unnecessary looping?
A single line approach?
Great Thanks for any help on this.
You can simplify it by using reverse regex and replace all allowed characters by empty string so that output will have only not-allowed characters left.:
var re = /[\w .#,\r\n*=:;&()'\/-]+/g
var input = '123.#&-_()/*=:/\';#$%^"~!?[]av'
var input = input.replace(re, '')
console.log(input);
//=> "#$%^"~!?[]"
Also note that many special characters don't need to be escaped inside a character class.

Escape single backslash inbetween non-backslash characters only

I have some input coming in a web page which I will re display and submit elsewhere. The current issue is that I want to double up all single backslashes that are sandwiched inbetween non-backslash characters before submitting the input elsewhere.
Test string "domain\name\\nonSingle\\\WontBe\\\\Returned", I want to only get the first single backslash, between domain and name.
This string should get nothing "\\get\\\nothing\\\\"
My current pattern that I can get closest with is [\w][\\](?!\\) however this will get the "\n" from the 1st test string i have listed. I would like to use lookbehind for the regex however javascript does not have such a thing for the version I am using. Here is the site I have been testing my regexs on http://www.regexpal.com/
Currently I am inefficiently using this regex [\w][\\](?!\\) to extract out all single backslashes sandwiched between non-backslash characters and the character before them (which I don't want) and then replacing it with the same string plus a backslash at the end of it.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
I don't care about any double, triple or quadruple backslashes present, they can be left alone.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
It will do just using replace, since you can insert the matched substring with $&, see:
console.log(String.raw`domain\name\\bl\\\ah`.replace(/\w\\(?!\\)/g, "$&\\"))
Easiest method of matching escapes, is to match all escaped characters.
\\(.)
And then in the replacement, decide what to do with it based on what was captured.
var s = "domain\\name\\\\backslashesInDoubleBackslashesWontBeReturned";
console.log('input:', s);
var r = s.replace(/\\(.)/g, function (match, capture1) {
return capture1 === '\\' ? match : '$' + capture1;
});
console.log('result:', r);
The closest you can get to actually matching the unescaped backslashes is
((?:^|[^\\])(?:\\\\)*)\\(?!\\)
It will match an odd number of backslashes, and capture all but the last one into capture group 1.
var re = /((?:^|[^\\])(?:\\\\)*)\\(?!\\)/g;
var s = "domain\\name\\\\escapedBackslashes\\\\\\test";
var parts = s.split(re);
console.dir(parts);
var cleaned = [];
for (var i = 1; i < parts.length; i += 2)
{
cleaned.push(parts[i-1] + parts[i]);
}
cleaned.push(parts[parts.length - 1]);
console.dir(cleaned);
The even-numbered (counting from zero) items will be unmatched text. The odd-numbered items will be the captured text.
Each captured text should be considered part of the preceding text.

javascript regex to return letters only

My string can be something like A01, B02, C03, possibly AA18 in the future as well. I thought I could use a regex to get just the letters and work on my regex since I haven't done much with it. I wrote this function:
function rowOffset(sequence) {
console.log(sequence);
var matches = /^[a-zA-Z]+$/.exec(sequence);
console.log(matches);
var letter = matches[0].toUpperCase();
return letter;
}
var x = "A01";
console.log(rowOffset(x));
My matches continue to be null. Am I doing this correctly? Looking at this post, I thought the regex was correct: Regular expression for only characters a-z, A-Z
You can use String#replace to remove all non letters from input string:
var r = 'AA18'.replace(/[^a-zA-Z]+/g, '');
//=> "AA"
Your main issue is the use of the ^ and $ characters in the regex pattern. ^ indicates the beginning of the string and $ indicates the end, so you pattern is looking for a string that is ONLY a group of one or more letters, from the beginning to the end of the string.
Additionally, if you want to get each individual instance of the letters, you want to include the "global" indicator (g) at the end of your regex pattern: /[a-zA-Z]+/g. Leaving that out means that it will only find the first instance of the pattern and then stop searching . . . adding it will match all instances.
Those two updates should get you going.
EDIT:
Also, you may want to use match() rather than exec(). If you have a string of multiple values (e.g., "A01, B02, C03, AA18"), match() will return them all in an array, whereas, exec() will only match the first one. If it is only ever one value, then exec() will be fine (and you also wouldn't need the "global" flag).
If you want to use match(), you need to change your code order just a bit to:
var matches = sequence.match(/[a-zA-Z]+/g);
To return an array of separate letters remove +:
var matches = sequence.match(/[a-zA-Z]/g);
You're confused about what the goal of the other question was: he wanted to check that there were only letters in his string.
You need to remove the anchors ^$, who match respectively the beginning and end of the string:
[a-zA-Z]+
This will match the first of letters in your input string.
If there might be more (ie you want multiple matches in your single string), use
sequence.match(/[a-zA-Z]+/g)
This /[^a-z]/g solves the problem. Look at the example below.
function pangram(str) {
let regExp = /[^a-z]/g;
let letters = str.toLowerCase().replace(regExp, '');
document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2## %hfr efg uor7 489(*&^% knt lhtkjj ngnm!##$%^&*()_');
<h4 id="letters"></h4>
You can do this:
var r = 'AA18'.replace(/[\W\d_]/g, ''); // AA
Also can be done by String.prototype.split(regex).
'AA12BB34'.split(/(\d+)/); // ["AA", "12", "BB", "34", ""]
'AA12BB34'.split(/(\d+)/)[0]; // "AA"
Here regex divides the giving string by digits (\d+)

How to check if a string has more than one of a certain character in a row in Javascript

I have a string that might have multiple commas in a row. I want to find every time it has more than one comma, I want it to be replaced with only one comma. How can I do this?
Thanks
Use a regular expression:
To test if a string contains multiple commas in a row:
var result = /,,/.test(input);
To replace them with just one:
var result = input.replace(/,+/g, ',');
To replace two or more consecutive commas with a single comma, you can use this:
str = str.replace(/,{2,}/g, ",");
The {2,} after the comma means two or more of whatever the preceeding character was in the regex.
The g flag tells it to replace all occurrences of that in the string.
Working demo: http://jsfiddle.net/jfriend00/pxhLH/
Use a simple loop and replace. Plug this into your page to see it work.
var str = ",,, I have ,, some extra ,, commas ,,";
while (str.indexOf(",,") > -1) {
str = str.replace(",,", ",")
}
alert(str);
The only part you need is the while loop. If you want you can make it into a function where str is the parameter and then kick out your new string.

Categories

Resources