Kavya Shree
Kavya Shree

Reputation: 1032

regex match starts and ends with expression using angular

I have my working example here

https://stackblitz.com/edit/angular-fk2vpr?embed=1&file=src/app/app.component.ts

here I wrote condition like if word starts and ends with { and } they need to highlight and in editable way. here its working fine for word which is having no space like {username} but in case of { host} then its not taking that word to highlight and also if somewords like {pas}!!

then word of {pas} alone needs to highlight but its taking along with that !!

Can anyone assist me what mistake I made on this scenario

Thanks in advance

Upvotes: 1

Views: 779

Answers (2)

Pujan Shah
Pujan Shah

Reputation: 835

Try with below code it will work.

 const editable = data.match(/{+.*?}+/gi);
  if(editable){
    editable.map(word => {
      const re= new RegExp(word,'g');
      data = data.replace(re,' '+ word.replace(/\s/gi,'')+' ')
    })
  }

enter image description here

As per above code the token {username}!! will not work as we are splitting with space. To resolve that problem we can do add extra space before and after of that token. Use below line to work in all condition.

data = data.replace(word, ' ' + word.replace(/\s/g,'') + ' ')

Upvotes: 1

Maciej B. Nowak
Maciej B. Nowak

Reputation: 1215

The problem lies with mapping the data.split(' '). Notice that when you call that on a string username { username} scrypt secret {password} you will not get an array with 5 elements, as you would like (i.e ['username', '{ username}', 'scrypt', 'secret', '{password}']), but it will split on every space character; so the resulting array looks more like this:

[
  'username',   '',
  '{',          '',
  '',           'username}',
  'scrypt',     'secret',
  '{password}'
]

If you can, I would advice on making the arr array as an array of arrays, each subarray consisting of words you want to launch a regex through. If this is, however, not an option, I would suggest not splitting like that, but mapping like this:

this.mappedArr = this.arr.map(data => {
    const editable = data.match('([{].*?[}])');
    console.log(editable);
    return {
      editable,
      data: !editable ? 
            data :
            data.match(/(\{+ *)?\w+( *\}+)?/g).map(word => ({word, editable: word.match('^[{].*?[}]$')})) <
    };
})

This begs for refactoring though, but it should work as an emergency fix.

Upvotes: 1

Related Questions