Reputation: 784
I have been trying to get a regular expression that can pick the last fourth character in the string.
For Ex. If "system" is a string I want to pick "s", I cannot check that from starting as the number of characters from start are not fixed.
So far I have only reached to : /.{3}$/g
, but it is taking last three character ans not the character after that.
Can someone help me in the same?
Upvotes: 0
Views: 2330
Reputation: 50164
.(?=.{3}$)
works with the whole expression matching, not just a capturing group.
Upvotes: 3
Reputation: 68
try using /([a-z]).{3}$/g
then in your result, you can use the value from first capture group. Change the class just in case you want a wider or different selection
Upvotes: 0
Reputation: 428
why not using substring like that :
function lastFourLetters(str)
{
if (str.length < 5)
return str;
return str.substring(str.length - 4 , 4);
}
Upvotes: 0
Reputation: 770
You’d have to use a group:
/(.).{3}$/
The full match here will be stem
, and group 1 would be s
(you can see for yourself here: https://regex101.com/r/dZwhcu/1)
You could solve it as follows:
var matches = 'system'.match(/(.).{3}$/); //=> ['stem', 's']
if (matches[1] === 's') {
// ...
}
Upvotes: 2
Reputation: 6282
const reg = /.*(.).{3}$/g
const str = 'this is astring'
console.log(
str.replace(reg, '$1')
)
Upvotes: 0