0

I have string that may contain any html elements , sentences , numbers etc stored in variable x now I want to find binding expression {{ }} and it's inner element in very effective way. I have program that mostly works fine but fails sometime so I am searching very effective way to do it.

function call(x){
   var  p = 0,
        d = [],
        g = x.replace(/\s/g, '');
    for(var i = p ; i< g.length; i++){
      x = x.substr(p,x.length - p);
      f1 = x.indexOf('}*');
      f2 = x.indexOf('*{');
      if(f1 == -1 || f2 == -1){
        break;
      }
      c = x.substr(f2+1,f1-f2);
      d.push(c.replace(/}|{/g,''))
      var p = f2+(c.length+2);
    }
   return d;
 }

var x = `<div> 
          <span class="*{race}*">
            *{name}*
          </span>
      </div>`;

    console.log(call(x));

This works fine in most of the cases but I am searching for more effective way and small idea to do this.

  • Please don't suggest idea using jquery

Alisha Sharma
  • 139
  • 2
  • 15
  • *mostly works fine but fails sometime* If you can share the test cases that are failing and succeeding, it will be possible/easier to modify/extend your existing solution itself. – gurvinder372 Jan 10 '18 at 05:52

1 Answers1

1

You can get the matches between two characters

function call(x){
   return x.match(/{(.*)}/g);
}

This will return the matches including { and }.

You can exclude them by using (?<={) (match but doesn't capture preceeding character) and (?=}) (match but doesn't capture succeeding character)

 return x.match(/(?<={)(.*)(?=})/g);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94