I have a string like this
const str = "Today is going to be @[City Temp](city-temp) in @[City Name](city-name)"
I want the output to be in handlebars syntax eg
const str = "Today is going to be {{city-temp}} in {{city-name}}"
I am having trouble trying to match this pattern.
I can see that if I do
str.replace(/[()]/g,"")
I get the string without the brackets.
But I can't work out how to search for the whole pattern something like the below where I find anything starting with @[
and ending with )
, I don't want to just start with @
by itself as there may be times in the string I don't want to remove the @
where it is not followed by a [
/[\@\[A-Za-z0-9\](A-Za-z0-9-)
CodePudding user response:
You can use
str = str.replace(/@\[[^\][]*]\(([^()]*)\)/g, "{{$1}}")
See the regex demo. Details:
@\[
- a@[
string[^\][]*
- zero or more chars other than[
and]
]\(
- a](
string([^()]*)
- Group 1 ($1
): any zero or more chars other than(
and)
\)
- a)
char.
See the JavaScript demo:
const str = "Today is going to be @[City Temp](city-temp) in @[City Name](city-name)"
console.log(str.replace(/@\[[^\][]*]\(([^()]*)\)/g, "{{$1}}"))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>