Extract number with decimals in string (Javascript) - javascript

i have this kind of string:
COMC1.20DI
I need to extract, in this case "1.20", but number can have decimals or not. How can I do it? I also need to get the start and end position of the number.
For starting position, I found
value.search(/\d/);
But I can't get any code to work for getting the last position of the number.
How can I do this?

This worked for me when I tried:
var value = 'COMC120DI';
alert(value.match(/[\d\.]+/g)[0]);
This returned "120". If you have multiple numbers in your string, it will only return the first. Not sure if that's what you want. Also, if you have multiple decimal places, it'll return those, too.

This is how I extracted numbers (with decimal and colon) from a string, which will return numbers as an array.
In my case, it had undefined values in the result array so I removed it by using the filter function.
let numArr = str.match(/[\d\.\:]+/g).map(value => { if (value !='.' && value !=':'){ return value } })
numArr = numArr.filter(function( element ) {
return element !== undefined;
});

You could try this snippet.
var match = text.match(/\d+(?:\.\d+)?/);
if (match) {
var result = 'Found ' + match[0] + ' on position ' + match.index + ' to ' + (match.index + match[0].length));
}
Note that the regex I'm using is \d+(?:\.\d+)?. It means it won't mistakenly check for other number-and-period format (i.e., "2.3.1", ".123", or "5.") and will only match integers or decimals (which is \d+ with optional \.\d+.
Check it out on JSFiddle.

var decimal="sdfdfddff34561.20dfgadf234";
var decimalStart=decimal.slice(decimal.search(/(\d+)/));
var decimalEnd=decimalStart.search(/[^.0-9]/);
var ExtractedNumber= decimalStart.slice(0,decimalEnd);
console.log(ExtractedNumber);
shows this in console: 34561.20

For extraction u can use this RegEx:
^(?<START>.*?)(?<NUMBER>[0-9]{1,}((\.|,)?[0-9]{1,})?)(?<END>.*?)$
The group "START" will hold everything before the number, "NUMBER" will hold any number (1| 1,00| 1.0) and finally "END" will hold the rest of the string (behind the number). After u got this 3 pieces u can calculate the start and end position.

Related

javascript - search(regex), get position of the last character of the matched string

In javascript, the String.search() returns the position (character index) of the character at the start of the match when there are multiple characters. Meaning, for example, if you try to regex search cde in abcdefghij, it returns 2 (where c is at) and not 4 (where e is at). How do I do this? I wouldn't just take the position, add by a fixed number, and you'll get the last character (Position + 2), that won't work if the match have varying length match.
Use match instead. You can use a capture group to add the length of the match.
const [, group, index] = "abcdfghij".match(/(cde?)/)
/* Make sure results are not undefined */
const lastIndex = index + (group.length - 1);
You could always create your own method.
function indexLastCharacter(string, search_word) {
let indexFirstCharacter = string.search(search_word);
return indexFirstCharacter + search_word.length;
}
console.log(indexLastCharacter("abcdefghij", "cde"))
// -> 5
I found out that the lookbehind also works, like (?<=y).*$ will return a position after y.

How to get the string value after the colon?

I really need your help,
How can I check a string to see if it has a ":" and then if it does, to get the string value after the ":"
ie.
var x = "1. Search - File Number: XAL-2017-463288"
var y = "XAL-2017-463288"
//check for the colon
if (x.indexOf(':') !== -1) {
//split and get
var y = x.split(':')[1];
}
Split on the colon, and grab the second member of the result. This assumes you want the first colon found.
var y = x.split(":")[1];
If the string didn't have a :, then y will be undefined, so a separate check isn't needed.
Or you could use .indexOf(). This assumes there's definitely a colon. Otherwise you'll get the whole string.
var y = x.slice(x.indexOf(":") + 1);
If you wanted to check for the colon, then save the result of .indexOf() to a variable first, and only do the .slice() if the index was not -1.

filter out a percentage from a string using a regular expression in javascript

I have the following string value: £-155 (-2.2%)
Out of that I want to be able to extract anything that is a number and may/may not contain a '-' minus sign. so the above would be: -2.2
I also need to know whether the value has a percentage in the form as above or not...a conditional statement will be used in the final code.
thoughts?
Why use regex for something so simple? Why not just grab the last character in the string and check if it's a digit or a %.
Likewise, if you want to remove it, just drop the last character from the string using the .substr() method:
http://www.w3schools.com/jsref/jsref_substr.asp
You basically want a regex that matches a number, which has been answered many times before.
Then once you have that, just add an optional percent symbol (%?) and check for its presence in the matched string.
// An optional sign and either an integer followed by an optional fraction
// or a decimal fraction.
var numberRe = '[+-]?(?:[0-9]+(?:[.][0-9]*)?|[.][0-9]+)';
// Matches a number (in group 1)
// and an optional percentage in parentheses (in group 2).
var quantity = new RegExp(
'(' + numberRe + ')(?:\\s*[(]\\s*(' + numberRe + ')\\s*%\\s*[)])?');
If you match with quantity you should get the number in group 1 and any percentage in group 2.
JSON.stringify(quantity.exec('£-155 (-2.2%)'))
["-155 (-2.2%)", "-155", "-2.2"]
To get them as numbers, use parseFloat or unary + as in
var match = quantity.exec('£-155 (-2.2%)');
var n = +match[1], pct = match[2] != null ? +match[2] / 100 : NaN;
alert('n = ' + n + ', whole = ' + (pct ? n / pct : "unknown"));

Regex using javascript to return just numbers

If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?
Regular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
To concatenate them:
'something102asdfkj1948948'.match( numberPattern ).join('')
Assuming you're not dealing with complex decimals, this should suffice I suppose.
You could also strip all the non-digit characters (\D or [^0-9]):
let word_With_Numbers = 'abc123c def4567hij89'
let word_Without_Numbers = word_With_Numbers.replace(/\D/g, '');
console.log(word_Without_Numbers)
For number with decimal fraction and minus sign, I use this snippet:
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;
const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)
console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
Update: - 7/9/2018
Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.
Update:
Here's another one with which you can even debugger regexp: Online regex tester and debugger.
Update:
Another one: RegExr.
Update:
Regexper and Regex Pal.
If you want only digits:
var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714
Now you get the digits joined
I guess you want to get number(s) from the string. In which case, you can use the following:
// Returns an array of numbers located in the string
function get_numbers(input) {
return input.match(/[0-9]+/g);
}
var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');
alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:
/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g
to:
/-?\d*\.?\d+/g
For example, this code:
"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)
generates this array:
["217","255","0","0","-0.8","-255","0","0","0","70.71"]
I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".
If you really want an array of numbers, you can convert the entire array in the same line of code:
array = whatever.match(/-?\d*\.?\d+/g).map(Number);
My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:
/-?[\d\.]+/g
var result = input.match(/\d+/g).join([])
Using split and regex :
var str = "fooBar0123".split(/(\d+)/);
console.log(str[0]); // fooBar
console.log(str[1]); // 0123
The answers given don't actually match your question, which implied a trailing number. Also, remember that you're getting a string back; if you actually need a number, cast the result:
item=item.replace('^.*\D(\d*)$', '$1');
if (!/^\d+$/.test(item)) throw 'parse error: number not found';
item=Number(item);
If you're dealing with numeric item ids on a web page, your code could also usefully accept an Element, extracting the number from its id (or its first parent with an id); if you've an Event handy, you can likely get the Element from that, too.
As per #Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.
This will prevent errors if no matches are found and return an empty string:
('something'.match( /\d+/g )||[]).join('')
Here is the solution to convert the string to valid plain or decimal numbers using Regex:
//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';
//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
const splitedValue = intitialValue.split('.');
//splittedValue = ['123','777','321'];
intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
//result i.e. initialValue = '123.777321'
}
If you want dot/comma separated numbers also, then:
\d*\.?\d*
or
[0-9]*\.?[0-9]*
You can use https://regex101.com/ to test your regexes.
Everything that other solutions have, but with a little validation
// value = '675-805-714'
const validateNumberInput = (value) => {
let numberPattern = /\d+/g
let numbers = value.match(numberPattern)
if (numbers === null) {
return 0
}
return parseInt(numbers.join([]))
}
// 675805714
One liner
I you do not care about decimal numbers and only need the digits, I think this one liner is rather elegant:
/**
* #param {String} str
* #returns {String} - All digits from the given `str`
*/
const getDigitsInString = (str) => str.replace(/[^\d]*/g, '');
console.log([
'?,!_:/42\`"^',
'A 0 B 1 C 2 D 3 E',
' 4 twenty 20 ',
'1413/12/11',
'16:20:42:01'
].map((str) => getDigitsInString(str)));
Simple explanation:
\d matches any digit from 0 to 9
[^n] matches anything that is not n
* matches 0 times or more the predecessor
( It is an attempt to match a whole block of non-digits all at once )
g at the end, indicates that the regex is global to the entire string and that we will not stop at the first occurrence but match every occurrence within it
Together those rules match anything but digits, which we replace by an empty strings. Thus, resulting in a string containing digits only.

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