Anderson
Anderson

Reputation: 341

can i improve this "regex"?

I have the following string:

const myString = '"{{ some text here }}"'

I want to remove the quotes before {{ and after }}. I can do:

myString.replace('"{{', '{{').replace('}}"', '}}')

But I'm wondering if there is a better way to achieve this without calling replace twice?

Does anyone can let me know if there is a better way and explain?

http://jsbin.com/xafovamihi/edit?js,console

Upvotes: 1

Views: 69

Answers (3)

MaxZoom
MaxZoom

Reputation: 7753

Why not to use regex to find {{ with }} and any text between?

const myString = '"{{ some text here }}"',
      reg = /{{.*?}}/;
console.log(myString.match(reg)[0]);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use a regex with an alternation group where you can capture {{ and }} into Group 1 and 2 respectively and replace with the backreferences only:

var myString = '"{{ some text here }}"';
console.log(myString.replace(/"({{)|(}})"/g, '$1$2'))

Details:

  • "({{) - matches " and captures {{ into Group 1
  • | - or
  • (}})" - captures }} into Group 2 and matches "

Since the replacement backreferences, when referencing a group that did not participate in the match, are initialized with an empty string, this $1$2 replacement will work properly all the time.

The global modifier /g will ensure all matches are replaced.

Upvotes: 2

Felix Guo
Felix Guo

Reputation: 2708

An easy way would be to combine the two patterns into one match using regex OR, so you get /"{{|}}"/g

Upvotes: 1

Related Questions