separate whole numbers and decimals from a string - javascript

I have a text string that can be as follows let str = '10x2.34' from which I would like to get only the numbers so try the following:
str.match(/\d+/g)
This ignores the characters and returns the numbers to me, but it only works for whole numbers, so how could I get the whole numbers and decimals, which can come in the following ways: let str = '10x2.34' or let str = '10x2,34'

Match digits with \d and punctuation with \. or , :
str.match(/[\d\.,]+/g)
const regex = /[\d\.,]+/g
console.log( "10x2.34".match(regex) ) // ["10","2.34"]
console.log( "10x2,34".match(regex) ) // ["10","2,34"]

Related

Find string( js search and regex) with backslashes and digits between them

I want to find a string in style of '/89/'
Let's say I have this string: '78/12/98 something else' and want to transform it into 'something else'.
And let's assume that not every string has to contain this type of expression(if the search function returns -1 we do nothing).
How to do this?
let string = '78/12/98 something else';
let index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string);
// OUTPUT: 'something else'
let string2 ='no double backslashes with digits between them';
index = string.search(look for description);
if(index!=-1){
string = string.substring(index+5);
}
console.log(string2);
// OUTPUT: 'no double backslashes with digits between them';
The pattern you are looking for is
Two digits / Two digits / Two digits space anything endline
\d\d/\d\d/\d\d\s(.*$)
or maybe
Zero or Two digits / Zero or Two digits / Zero or Two digits space anything endline
\d{0,2}/\d{0,2}/\d{0,2}\s(.*$)
replace with
\1 It will replace with anything it matched inside ().
For JS you can do as follow
let string = '78/12/98 something else';
let patt = /\d{0,2}\/\d{0,2}\/\d{0,2}\s/; // Creates a regex patern
string = string.replace(patt, ''); // replace finds with ''
enter image description here

Finding \ inside a string

I need to validate a string that it's an actual number.
let str = '\n2';
But Number(str) returns 2 instead of NaN.
How can I check if the given string contains any backslash?
\n inside a string literal is interpreted as a newline character, and newline characters, like all space characters, are just skipped over when you try to turn the string into a number:
// these are all whitespace characters
console.log(
Number(' 5'),
Number('\n5'),
Number('\t5'),
);
If you want to extract a number only if the string contains only number characters and nothing else, I'd match digits with a regular expression instead:
const extractNum = str => {
const match = str.match(/^\d+$/);
return match
? Number(match[0])
: NaN;
};
console.log(
extractNum('\n5'),
extractNum('5')
);
To permit decimals as well:
const extractNum = str => {
const match = str.match(/^\d*(?:\.\d+)?$/);
return match
? Number(match[0])
: NaN;
};
console.log(
extractNum('\n5'),
extractNum('5'),
extractNum('0.123'),
extractNum('.55')
);

Get number(decimal digit) from String

I see somebody already asked this question but the result is not really in the case of number is decimal digit.
Example:
var str = "textsometext13.523 after text";
Then if I use str.replace(/[^0-9]/gi, '');
It will return 13523 instead of 13.523
How I can use new regex to get it?
Thank you very much.
If you know your input string will only contain one number and not have a full stop at the end then simply update your regex to include a . in the list of characters to keep:
/[^0-9.]/gi
But if you need to allow for input like the following:
"text 123.12 text 13"
"The numbers are 132.12, 144.11, and 123.1."
...then you should use the .match() method, which with the right regex will return an array of matched numbers (or return null if there were no matches):
var results = input.match(/\d+(?:\.\d+)?/g);
That is, match one or more digits \d+, that are optionally followed by a decimal \. and one or more digits \d+.
Demo:
console.log( "text 123.12 text".match(/\d+(?:\.\d+)?/g) );
console.log( "The numbers are 132.12, 5, and 123.1.".match(/\d+(?:\.\d+)?/g) );
console.log( "No numbers".match(/\d+(?:\.\d+)?/g) );
You can use RegExp /\d+\.\d+|\d+/g to match digits followed by . character followed by digits, or one or more digits
str.match(/\d+\.\d+|\d+/g)
You can try this one:
var string = "textsometext13.523 after text";
var number = string.match(/[\d\.]+/).toString();
var num = number.split('.');
alert(num[1]); //display the numbers after the period(.) symbol
simply use like this /\d+(?:\.\d+)?/g:
console.log("textsometext13.523 after text".match(/\d+(?:\.\d+)?/g,""))
Alternate, its the reverse process replace the [a-z] same thing will append
console.log("textsometext13.523 after text".replace(/[a-z]/g,""))
This regex should match any number whether it has a decimal or not:
/(\d*\.?\d*)/g
SNIPPET
var btn1 = document.getElementById('btn1');
var inp1 = document.getElementById('inp1');
var out1 = document.getElementById('out1');
btn1.onclick = function() {
var str = inp1.value
var res = str.match(/\d*\.?\d*/g);
out1.innerHTML = res;
}
<input id='inp1'>
<input id='btn1' type='button' value='Extract Numbers'>
<output id='out1'></output>

How to write regular expression to filter out string with single occurence of 4 in , separated string array

In the below example I need to get the strings which have only 4 and not 44.
var strs = ["3,4,6","4,5,6","1,2,3,4","44,55","55,44","33,44,55"];
var patt = new RegExp(/[,|^\d]*4[,|^\d]*/);
for(i in strs){
var str = strs[i];
var res = patt.test(str);
if(res){
console.log(str);
}else{
console.error(str);
}
}
^(?!.*(\d4|4\d)).*4.*$
(?!.*(\d4|4\d)) it ensure that no string should not contain any digit contain 4 and greater than 10.
.*4.* ensure that string contain at least 1 "4".
Demo
Try
^(?!.*(\d4|4\d).*).*$
It uses a negative look-ahead to assert that there isn't a combination of 4 followed by a digit, or the other way around.
See it here at regex101.

What's a good RegExp that will strip out all characters except Integers from a string?

I'm new to using regexp, can someone give me the regexp that will strip out everything but an integer from a string in javascript?
I would like to take the string "http://www.foo.com/something/1234/somethingelse" and get it down to 1234 as an integer.
Thanks
var str = "something 123 foo 432";
// Replace all non-digits:
str = str.replace(/\D/g, '');
alert(str); // alerts "123432"
In response to your edited question, extracting a string of digits from a string can be simple, depending on whether you want to target a specific area of the string or if you simply want to extract the first-occurring string of digits. Try this:
var url = "http://www.foo.com/something/1234/somethingelse";
var digitMatch = url.match(/\d+/); // matches one or more digits
alert(digitMatch[0]); // alerts "1234"
// or:
var url = "http://x/y/1234/z/456/v/890";
var digitMatch = url.match(/\d+/g); // matches one or more digits [global search]
digitMatch; // => ['1234', '456', '890']
This is just for integers:
[0-9]+
The + means match 1 or more, and the [0-9] means match any character from the range 0 to 9.
uri = "http://www.foo.com/something/1234/somethingelse";
alert(uri.replace(/.+?\/(\d+)\/.+/, "$1"))
Just define a character-class that requires the values to be numbers.
/[^0-9]/g // matches anything that is NOT 0-9 (only numbers will remain)

Categories