2

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.

2
  • What have you tried? Regular expressions are a language feature and therefore have nothing to do with jQuery. Commented Feb 14, 2013 at 20:28
  • 1
    does 'an integer' include more than one digit? That is, should 'sdgab345' return 'ab345'? Commented Feb 14, 2013 at 20:30

4 Answers 4

8

The 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 
Sign up to request clarification or add additional context in comments.

Comments

2

One way using replace:

str.replace(/.*(ab\d+)$/, "$1"); 

Another way using match:

(str.match(/ab\d+$/) || [""]).pop(); 

Comments

1
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"

Comments

1

Use $ to match the end of the string:

'foo2'.match(/[a-z]{2}\d$/); 

2 Comments

This also matches any other two lower-case letters e.g. "no1". That wasn't asked!
@MartinM.: Well, I interpreted ab as being [a-z]{2}, not literally the characters ab.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.