I have a string as a1234b5.
I am trying to get 1234 (in between a and b5). i tried the following way
number.replace(/[^0-9\.]/g, '');
But it's giving me like 12345. But I need 1234. how to achieve this in Javascript ?
You can use:
var m = 'a1234b5'.match(/\d+/);
if (m)
console.log(m[0]);
//=> "1234"
1a2345b will return 1 instead of 2345. To me this isn't the "right" regex but rather the "most simple" regex that fits for an arbitrary interpretation.slighty different approach
var a = "a1234b5243,523kmw3254n293f9823i32lia3un2al542n5j5j6j7k7j565h5h2ghb3bg43";
var b;
if ( typeof a != "undefined" )
{
b = a.match( /[0-9]{2,}/g );
console.log( b );
}
no output if a isn't set.
if a is empty => null
if somethings found => ["1234", "5243", "523", "3254", "293", "9823", "32", "542", "565", "43"]
var number = 'a1234b5';
var firstMatch = number.match(/[0-9]+/);
var matches = number.match(/[0-9]+/g);
var without = matches.join('');
var withoutNum = Number(without);
console.log(firstMatch); // ["1234"]
console.log(matches); // ["1234","5"]
console.log(without); // "12345"
console.log(withoutNum); // 12345
I have a feeling that number is actually a hexadecimal. I urge you to update the question with more information (i.e. context) than you're providing.
It's not clear if a and b are always part of the strings you are working with; but if you want to 'extract' the number out, you could use:
var s = "a1234b5",
res = s.match(/[^\d](\d+)[^\d]/);
// res => ["a1234b", "1234"]
then, you could reassign or do whatever. It's not clear what your intention is based on your use of replace. But if you are using replace to convert that string to just the number inside the [a-z] characters, this would work:
s.replace(/[^\d](\d+)[^\d](.*)$/, "$1")
But, that's assuming the first non-digit character of the match has nothing before it.
aandbthat surround the numbers you want? What other rules apply to your text that we don't know of?