How did you use the flag g
, the method match
returns an array containing all parts found (except capture groups, but since your regex doesn’t have that, then okay).
So at the bottom, it all comes down to turning an array into a string. And then it depends, there are several ways to do it.
In your specific case, if you "know" that you will only have one occurrence, you can simply take the first element of the array:
let value = ">>>> Ola";
let result = value.match(/\w+/g);
if (result) {
console.log(result[0]);
}
I check whether result
is valid, because when no one is found match, the method match
returns null
(and in that case, there’s nothing to print).
If there is the possibility of returning more than one match, then just go through the array and get the strings one by one:
let value = ">>>> Ola, mundo";
let result = value.match(/\w+/g);
if (result) {
result.forEach(s => console.log(s));
}
Or still use join
, for example, to show all strings concatenated at once:
let value = ">>>> Ola, mundo";
let result = value.match(/\w+/g);
if (result) {
console.log(result.join(', '));
}
Anyway, once you have the array with the strings found, you decide the best way to show them.
Is giving error 'Object is possibly 'null'. Only working in Javascript
– Isaac
I’ll update the reply
– Vinicius Farias
The Object is possibly 'null' problem occurred because the return of the match function could be null, I made a ternary IF so that when null, assign '' to the string
– Vinicius Farias