Parsing number from string - javascript

How do I split selected value, seperate the number from text in jQuery?
Example:
myselect contains c4
Just get only the number 4.
$('select#myselect').selectToUISlider({
sliderOptions: {
stop: function(e,ui) {
var currentValue = $('#myselect').val();
alert(currentValue);
var val = currentValue.split('--)
alert(val);
}
}
});

You can use regex to pull only the numbers.
var value = "c4";
alert ( value.match(/\d+/g) );
edit: changed regex to /\d+/g to match numbers greater than one digit (thanks #Joseph!)

1) if it's always : 1 letter that followed by numbers you can do simple substring:
'c4'.substring(1); // 4
'c45'.substring(1); // 45
2) you can also replace all non-numeric characters with regular expression:
'c45'.replace(/[^0-9]/g, ''); // 45
'abc123'.replace(/[^0-9]/g, ''); // 123

If you know that the prefix is always only one character long you could use this:
var val = currentValue.substr(1);

Related

Regex for getting only the last N numbers in javascript

I've being trying to generate a regex for this string:
case1: test-123456789 should get 56789
case2: test-1234-123456789 should get 56789
case3: test-12345 should fail or not giving anything
what I need is a way to get only the last 5 numbers from only 9 numbers
so far I did this:
case.match(/\d{5}$/)
it works for the first 2 cases but not for the last one
You may use
/\b\d{4}(\d{5})$/
See the regex demo. Get Group 1 value.
Details
\b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
\d{4} - four digits
(\d{5}) - Group 1: five digits
$ - end of string.
JS demo:
var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) {
var m = s.match(rx);
if (m) {
console.log(s, "=>", m[1]);
} else {
console.log("Fail for ", s);
}
}
You can try this:
var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);
This way supports default value for when not found any matching (look at inserted comment inline above code.).
You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.
/(?<=\d{4})\d{5}$/
var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]
var rgx = /(?<=\d{4})\d{5}$/
inputs.forEach(str => {
console.log(rgx.exec(str))
})

Removing all instances of a character from a string

I'm attempting to remove all instances of a given set of characters £$€,. from a string in jQuery/Javascript. I'm using the replace function, however this only appears to remove a single instance of the character and not all of them.
For example consider the string:
1,500,00.00.$djdjd£10€10
I get back:
1500,0000.djdjd1010
As you can see, it only removes a single instance of each character. £, $ and € are fine as there is only one of each in the string.
Here is what I have so far:
function validatePriceRange(value, min, max) {
var replacements = ["£", "$", "€", ",", "."];
$.each(replacements, function (index, item) {
value = value.replace(item, "");
});
var value = parseInt(value, 10);
return value >= min && value <= max;
}
jsFiddle
Can anyone spot what I've done wrong?
replace called with a string as first argument does only one replacement, while using a regular expression with flag g replaces all occurrences.
Using a regular expression, you can also avoid looping over an array and do it in one pass :
value = value.replace(/£|\$|€|,|\./g,'');
You are only cycling through your replacement array once and replace everytime the specific character.
But replace is only replacing the first occurance of a given string.
For a replace all method, look here.
I don't think you need a function for it:
var validated = parseInt('1,500,00.00.$djdjd£10€10'.replace(/[£$€,.]/g,''), 10);
//=> 15000000
// or if you want the validated directly
var validated = function(min,max) {
var v = parseInt('1,500,00.00.$djdjd£10€10'
.replace(/[£$€,.]/g,''), 10);
return v >= min && v <==max;
}(1000, 200000); //=> false
The regular expression should be different if you want to include all digits in the string:
var validated = function(min,max) {
var v = parseInt('1,500,00.00.$djdjd£10€10'
.replace(/[^\d]/g,''), 10);
// ^ replace non numbers
// v now is 150000001010
return v >= min && v <==max;
}(1000, 200000); //=> false
Use a regex with the global flag, which will search and replace all instances
var replacements = ["£", "\\$", "€", ",", "\\."];
$.each(replacements, function (index, item) {
value = value.replace(new RegExp(item, "g"), '');
});
Demo: Fiddle
As already answered here you could use the following regex that replaces all non characters and whitespaces with empty.
var value = "1,500,00.00.$djdjd£10€10"
value = value.replace(/[^\w\s]/gi, '')

Change a string with javascript

I'm checking a string with this regular expression:/^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/. This allows a total of 9 different formats, being: XXXXX, XXX-XX, XXX XX, SEXXXXX, SEXXX-XX, SEXXX XX, SE XXXXX, SE XXX-XX and SE XXX XX (X:s being any number from 0-9). How do I change the format to XXXXX after the check passes for one of the 9 valid formats?
I've read a bunch of other threads about the string.replace()-method but I can't seem to make it work. Here's my code so far:
var pcValue = postalCode.value;
var format = /^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/;
if (format.test(pcValue) === true) {
pcValue = pcValue.replace(/\[SE]*[\s]*[\s\-]*$/, /^[0-9]{5}$/);
}
What it gives me is a string with /^[0-9]{5}$/ instead of the XXXXX format I wanted.
You can do this :
var format = /^([SE]*)\s*(\d{3})[\s\-]*(\d\d)$/;
if (format.test(pcValue)) {
pcValue = pcValue.replace(format, "$2$3");
}
Note that if you don't do anything else than replacing if test returns true, then you don't have to test at all, just execute the replacement.
Try this:
var pcValue = postalCode.value;
pcValue = pcValue.replace(/^[SE]*[\s]*([0-9]{3})[\s\-]*([0-9]{2})$/, "$1$2");
Demo
http://jsfiddle.net/uLJEm/
var pcValue = postalCode.value;
var format = /^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/;
if (format.test(pcValue) === true) {
pcValue = pcValue.replace(/\[SE]*[\s]*[\s\-]*$/, /^[0-9]{5}$/);
}
str.replace(original,replicant);
The answer you've marked as accepted also validates these kinds of inputs :
"ES 12345"
"SSSSS 123 - 45"
"SESE 123---45"
The following regular expression might better fit with your needs :
function parse(input) {
var re = /^(?:SE)?\s?(\d{3})(?:\s|-)?(\d\d)$/;
return re.test(input) && input.replace(re, '$1$2');
}
var input1 = parse('SE 123 45'); // 12345
var input2 = parse('ES 123 45'); // false
input1 || alert('Please fix input #1!');
input2 || alert('Please fix input #2!'); // alert!
A little help about /^(?:SE)?\s?(\d{3})(?:\s|-)?(\d\d)$/ :
^...$ string boundaries
(...) capture match
(?:...) don't capture match
(?:SE)? "SE", zero or one time
\s? a whitespace, zero or one time
(\d{3}) 3 digits (captured -> $1)
(?:\s|-)? a whitespace or a dash, zero or one time
(\d\d) 2 digits (captured -> $2)
More on regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.

How to check for uppercase alphabets in an input string, using jQuery

I am using following code snippet, but its not working :-(
//First four characters of input Text should be ALPHABATES (Letters)
if (($("#txtId").val()).length >= 4) {
var firstFourChars = $("#txtId").val().substring(0, 4);
var pattern = new RegExp('[^A-Z]');
if (firstFourChars.match(pattern))
isValid = true;
else
isValid = false;
}
change /[^A-Z]/ to /^[A-Z]/
example :
var a = "ABCJabcd";
console.log(a.match(/^[A-Z]{4}/));
you don't need to use substring(). Your regexp can do all the work for you. The RegExp you are using matches against characters that are NOT between A and Z. As Avinash said, ^[A-Z]{4} will match if your first 4 characters are uppercase. "^" at the beginning of your regexp tells that the following should be the beginning of the string. When placed inside square brackets, it reverts the range of characters you want to match.
The regex should be /[^A-Z]{4}/ if you want to match the 4 lowercase characters.
To detect in the middle of the big papers change /^[A-Z]/ to /[A-Z]/
Example text: " asşldla ABCJ abcd AÇALASD"
$('.Order input').change(function (){ucheck($(this).val())});
$('.Order input').keyup(function (){ucheck($(this).val())});
function ucheck(a) {
if(a.match(/[A-ZĞÜŞİÖÇ]{4}/)){
$('.Order #Error').html(' UPPERCASE');
}else{$('.Order #Error').html('Capitalize');}
}
If they need to be capital:
const startsWithCapitals = /^[A-Z]{4}/.test(string);
Or if they just need to be letters, add an i for ignore case:
const startsWithLetters = /^[a-z]{4}/i.test(string);
^ means start of the string and {number} means x copies

How to match with javascript and regex?

I have the following HTML:
<span id="UnitCost5">$3,079.95 to $3,479.95</span>
And i want to use Javascript and Regex to get all number matches.
So i want my script function to return: 3,079.95 AND 3,479.95
Note the text may be different so i need the solution as generic as posible, may be it will be like this:
<span id="UnitCost5">$3,079.95 And Price $3,479.95</span>
All the numbers would be matched by:
\.?\d[\d.,]*
This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives):
\d[\d.,]*
Be aware that different local customs exist in number formatting.
I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.
You don't want to capture all numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: $#,###.##
Here goes the expression for that:
/\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/
\$ The dollar sign
[0-9]{1,3} One to three digits
(,[0-9]{3})* [Optional]: Digit triplets, preceded by a comma
(\.[0-9]+)? [Optional]: Even more digits, preceded by a period
/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
Let's break that into parts for explanations:
(?:\d{1,3},)* - Match any numbers separated by a thousand-divider
\d{1,3} - Match the numbers before the decimal point
(?:.\d+) - Match an arbitrary number of decimals
Flag 'g' - Make a global search to find all matches in the string
You can use it like this:
var regex = /(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
var numbers = "$3,079.95 And Price $3,479.95".match(regex);
// numbers[0] = 3,079.95
// numbers[1] = 3,479.95
A very simple solution is the following one. Note that it will also match some invalid number strings like $..44,.777.
\$[0-9,.]+
(function () {
var reg = /\$([\d\.,]+)\s[\w\W]+\s\$([\d\.,]+)$/;
// this function used to clean inner html
function trim(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function getNumbersFromElement(elementId) {
var el = document.getElementById(elementId),
text = trim(el.innerHTML),
firstPrice,
secondPrice,
result;
result = reg.exec(text);
if (result[1] && result[2]) {
// inside this block we have valid prices
firstPrice = result[1];
secondPrice = result[2];
// do whatever you need
return firstPrice + ' AND ' + secondPrice;
} else {
return null; // otherwise
}
}
// usage:
getNumbersFromElement('UnitCost5');
})();
The following will return an array of all prices found in the string
function getPrices(str) {
var reg = /\$([\d,.]+)/g;
var prices =[];
var price;
while((price = reg.exec(str))!=null) {
prices.push(price);
}
return prices;
}
edit: note that the regex itself may return some false positives

Categories

Resources