skip to Main Content

I am building an Angular 9 app.
In this app I am creating search filters for the Shopify Graphql API.

I am building a query and the result is:

first: 1, query: "tag:'featured-1'", after: 'eyJsYXN0X2lkIjo32MjYzMTI0MDAwO3TQxLCJsY3XN0X3ZhbHVlIjo2MjYzMTI0MDAwOTQxfQ=='

The result is a string. I want to replace the value for after (inside the ‘ ‘) and if there is no new value for after: ” I want to remove it.

In other words, how can I replace the below value or if the next one is empty remove it from the string?

eyJsYXN0X2lkIjo32MjYzMTI0MDAwO3TQxLCJsY3XN0X3ZhbHVlIjo2MjYzMTI0MDAwOTQxfQ==

2

Answers


  1. The way you post the result looks like a JSON, can’t you just set .after = ” ?

    If not, this replace should do the job:

    let emptyAfterPropRegex = /(, after:'')/;
    let nonEmptyAfterPropRegex = /after:'.+'/;
    
    if (emptyAfterPropRegex.test(result)){
      result.replace(emptyAfterPropRegex, '');
    } else {
      result.replace(nonEmptyAfterPropRegex, 'after:'Whatever you want past here'')
    }
    

    note that for this, I assume the ‘ comes right after : inside the string, like such:

    "after:'eyJsYXN0X2lkIjo32MjYzMTI0MDAwO3TQxLCJsY3XN0X3ZhbHVlIjo2MjYzMTI0MDAwOTQxfQ=='"
    

    If not, either add a space in the regex or even remove brackets if necessary..

    Login or Signup to reply.
  2. function replace(str) {
      var newStr = str.replace(/,? *bafter *: *''/, '')
      newStr = newStr.replace(/(bafter *: *').+?'/, `$1'`)
    
      return newStr
    }
    
    console.log(replace('') === '')
    console.log(replace(`after:''`) === '')
    console.log(replace(`after: ''`) === '')
    console.log(replace(`before: 1, after:''`) === 'before: 1')
    console.log(replace(`after:'23'`) === `after:''`)
    console.log(replace(`after: '23'`) === `after: ''`)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search