I want to check if a string ends with ab
followed by an integer.
Given any string s
, how can I first check if it ends with ab1
or ab2
or ab3
, and if so, return ab1
or ab2
or ab3
.
For example, for string sdfsadfsab2
, I want to return ab2
.
For string asdfase
I want to return empty string.
Is there any regular expression in javascript or jquery can do this? thanks.
I want to check if a string ends with ab
followed by an integer.
Given any string s
, how can I first check if it ends with ab1
or ab2
or ab3
, and if so, return ab1
or ab2
or ab3
.
For example, for string sdfsadfsab2
, I want to return ab2
.
For string asdfase
I want to return empty string.
Is there any regular expression in javascript or jquery can do this? thanks.
Share Improve this question edited Feb 14, 2013 at 20:29 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Feb 14, 2013 at 20:25 neoneo 2,4719 gold badges44 silver badges67 bronze badges 2- What have you tried? Regular expressions are a language feature and therefore have nothing to do with jQuery. – Felix Kling Commented Feb 14, 2013 at 20:28
- 1 does 'an integer' include more than one digit? That is, should 'sdgab345' return 'ab345'? – PinnyM Commented Feb 14, 2013 at 20:30
4 Answers
Reset to default 8The regex you're after could well be:
/ab[0-9]$/
If you want a tester function, that function could look something like this:
function testABInt(string)
{
var match = string.match(/ab[0-9]$/);
return match ? match[0] : '';
}
This only matches the end of a string if ab
are lower-case chars, and if there is only one int at the end, to match case-insensitive, add the i
flag, and/or add a +
to match all trailing digits:
/ab[0-9]+$/i
One way using replace
:
str.replace(/.*(ab\d+)$/, "$1");
Another way using match
:
(str.match(/ab\d+$/) || [""]).pop();
var regex = /([a-zA-Z]{2}[0-9])$/;
var str = "sdfsadfsab2";
console.log(str.match(regex)[0]); //outputs "ab2"
Explanation of regex:
[a-zA-Z]
- a collection of the letters from a-z in lower and upper case{2}
- meaning "repeated exactly 2 times"[0-9]
- a collection of the digits from 0 to 9$
- meaning "end of the string"
Use $
to match the end of the string:
'foo2'.match(/[a-z]{2}\d$/);