Input
ABC - MMM
Expected output
MMM
Everything after -
and a space
Tried this (-\s).+
But I dont get rid of - and space.
Input
ABC - MMM
Expected output
MMM
Everything after -
and a space
Tried this (-\s).+
But I dont get rid of - and space.
So there are multiple ways to go about this. The easiest and potentially best method is not to use regex at all.
Method 1 - split
Of course, you'd add a check to ensure that the element [1]
exists, but this shows you the general idea of getting MMM
.
console.log("ABC - MMM".split(" - ")[1])
Method 2 - regex group
This method groups everything you want into capture group 1.
console.log("ABC - MMM".match(/-\s(.+)/)[1])
Method 3 - regex lookbehind
This one was suggested by Andrew Bone in his answer here. While this works, it's currently only supported on Chrome 62+ (lookbehinds have little support in browsers at the moment). You can see the RegExp Lookbehind Assertions proposal here as part of EMCA TC39.
console.log("ABC - MMM".match(/(?<=-\s).+/)[0])
You want to use positive lookbehind
which means look for things after, but not including, a pattern. The syntax is ?<=
(?<=-\s).+
Here is some further reading
Though this is the correct way to do this it's worth noting, as @ctwheels points out, support is currently very limited.
EDIT:
You can use split to turn the string into an array and then return the last string in the array.
This is a slightly long winded way to do it but I think it is more readable this way.
var string = "ADSD - ASDASD";
var regex = /(-\s)/;
function matchAfter(string, pattern) {
var short = string.split(pattern);
return short[short.length - 1];
}
console.log(matchAfter(string, regex));
You can capture the groups and get the last element from the array.
console.log(("ABC - MMM".match(/-\s+(.+)/) || []).pop());