skip to Main Content

I have multiple TypeScript files with this object structure:

const x = {
    abc: {
        foo: {
            bar1: true,
            bar2: false,
            bar3: true,
        },
        bar: {
            baz1: false,
            baz2: false,
            baz3: true,
        }
    }
}

Note: this is the type { abc: { foo: { [P in string]: boolean }, bar: { [P in string]: boolean } } }

How can I use a regex "find and replace" in VS code to replace all values ONLY inside foo object? I want to replace all true values inside foo with 'supported' and all the false values in the foo object with 'not-supportes'.

Is there a way to find and replace conditionally?
I don’t mind replacing all true values first and all false after, but it has to be only inside foo.

I tried a bunch of different regexs but can’t figure out how to match all true|false values. And even if I can get all of them matched, how do I replace all of the in the replace statement?

2

Answers


  1. do a regex find for : (foo: *{[nw: ,'-]+?)(true)

    replace with: $1'supported'

    Apply as often till VSC tells you no replacements made.

    The same for false

    do a regex find for : (foo: *{[nw: ,'-]+?)(false)

    replace with: $1'not-supported'

    As often till no replacement made

    Login or Signup to reply.
  2. You could just use the "Find in Selection" toggle button of the find widget. First, select the following from the inside of x.abc.foo:

                bar1: true,
                bar2: false,
                bar3: true,
    

    Then open the find widget with ctrl/cmd+f, then enable "Find in Selection" by clicking its toggle button, then put : true in the search field, then put : 'supported' in the replace field, then use the "Replace All" action, then repeat the process for replacing false with 'not-supported'.

    I think rioV8’s answer works better when you have a lot of files and not many object property values to replace, but mine works better when you have a few files with many object property values to replace, since my solution needs to be repeated for as many files as you want to do this in, but rioV8’s solution apparently requires clicking a button as many times as there are property values to replace in the file with the most property values to replace.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search