regex to get the number from the end of a string - javascript

i have a id like stringNumber variable like the one as follows : example12
I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.

This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.
Before accessing the 0 member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number, you can use a function to convert it, such as parseInt().
number = parseInt(number, 10);

RegEx:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);

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))

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)

What does this obfuscated javascript snippet mean/do?

I cannot understand what this little snippet: var num = str.replace(/[^0-9]/g, ''); does.
Context:
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
var liczba = parseInt(num);
return liczba;
}
This JavaScript snippet will rip out anything that is not (the ^ part of the regular expression means "not") a number in str and then return an integer cast from the result as liczba. See my comments:
// This function will return a number from a string that may contain other characters.
// Example: "1.23" -> 123
// Example: "a123" -> 123
// Example: "hg47g*y#" -> 47
function retnum(str) {
// First let's replace everything in str that is not a number with "" (nothing)
var num = str.replace(/[^0-9]/g, '');
// Let's use JavaScript's built in parseInt() to parse an Integer from the remaining string (called "num")
var liczba = parseInt(num);
// Let's now return that Integer:
return liczba;
}
By the way, "liczba" means number in Polish :-)
This function takes a string, strips all non-number characters from it, turns the string into an integer, and returns the integer. The line you're asking about specifically is the part that strips out all non-number characters from the initial string, using the string.replace method.
It's not obfuscated, it's using a regular expression.
The expression matches all things which are not numbers then removes them. 0-9 means "any digit" and the ^ means "not". The g flag means to check the entire string instead of just the first match. Finally, the result is converted to a number.
Example:
var input = 'abc123def456';
var str = input.replace(/[^0-9]/g, '');
var num = parseInt(str);
document.querySelector('pre').innerText = num;
<pre></pre>
It literally just replaces anything which is not a number with a blank ('').

Javascript extract numbers from a string

I want to extract numbers from a string in javascript like following :
if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.
Possible string values :
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
thinking of something like :
function beforeTo(string) {
return numeric_value_before_'to'_in_the_string;
}
function afterTo(string) {
eturn numeric_value_after_'to'_in_the_string;
}
i will be using these returned values for some calculations.
Here's an example function that will return an array representing the two numbers, or null if there wasn't a match:
function extractNumbers(str) {
var m = /(\d+)to(\d+)/.exec(str);
return m ? [+m[1], +m[2]] : null;
}
You can adapt that regular expression to suit your needs, say by making it case-insensitive: /(\d+)to(\d+)/i.exec(str).
You can use a regular expression to find it:
var str = "sure1to3";
var matches = str.match(/(\d+)to(\d+)/);
if (matches) {
// matches[1] = digits of first number
// matches[2] = digits of second number
}

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