Reputation: 587
I'm currently on https://regex101.com/ and have the following inputted (with global flag):
REGULAR EXPRESSION: ([A-Z])
TEST STRING: ABCdefGHI
On the right in Match Information
the following string is in Group 1: ABCGHI
I'm trying to replicate this in JavaScript and I'm having trouble:
var myString = "ABCdefGHI";
var myRegexp = /([A-Z])/g;
var match = myRegexp.exec(myString);
console.log(match[1]);
The above just returns A
. Desired result: ABCGHI
I've looked around a bit and there seems to be a way to do it by looping through the resulting RegEx grouping array, pushing all elements, and then doing a string join. I'm wondering if that is completely necessary or if I'm missing something obvious.
Upvotes: 1
Views: 123
Reputation: 784958
You can use array.join('')
where array
is return value of string.match(re)
:
var myString = "ABCdefGHI";
var myRegexp = /([A-Z])/g;
var result = myString.match(myRegexp).join('');
console.log(result);
//=>"ABCGHI"
Or else if you're allowed to change regex then use negation:
var repl = myString.replace(/[^A-Z]+/, '')
//=> "ABCGHI"
Upvotes: 3