I have a string like this: "hello %{name} good %{middle} bye"
.
I’m trying to find an effective way to extract out the values in-between the braces, so ideally I would end up with an array of ["name", "middle"]
.
Using match
I can almost get there. The following returns: ['%{name}', '%{middle}']
:
"hello %{name} good %{middle} bye".match(/%{([w]+)}/g)
I’m not sure why it’s including the %
, {
, and }
characters in the return though.
How can I adjust my regular expression to only match name
and middle
?
3
Answers
You can use a named capturing group. In the example below, we name it
value
, and then extract those values during iteration of the regex matches:Try
Regards your question why is it including the %, {, and } characters in the return
because the match() function in JavaScript returns the entire matched substring, including the %{ and }.
A solution to this would be to use match[1] (or equivalent in a loop with exec()) allows you to access only the content captured within the parentheses ( ) in your regex pattern.
You need to change your regex expression to capture the values inside the braces without the %, {, and } characters, you can modify it slightly.
Existing:
/%{([w]+)}/g
=>/%{(w+)}/g
Refer the below examples:
Also, this can be achieved via non regex-based approach as well: