2

Solved: Replace array-mapped variables with the actual variable name/string?

I'm trying to decode some JS and I've got a good portion of it done, however, I'm stumped here. The code does something like this:

var arr = ["value", "value1", "value2"];
console.log(arr[0]);

Except the file is around 12k lines and there are over 1.4k things in the array. Is there a way I can replace arr[0] with the actual value of arr[0] (in the example, it would be "value"), then save the file? I tried using RegExp but got nowhere.

Any help will be appreciated.

16
  • Did you write to write the output into a file? node script.js > myfile.txt Commented Apr 28, 2017 at 5:43
  • @Rahul I tried to iterate through it and then replace the array and value with the actual one but I just couldn't work the logic out. Commented Apr 28, 2017 at 5:50
  • @EliR: Please add that in your post along with code if possible. Commented Apr 28, 2017 at 5:51
  • Your question is unclear. What is the nature of your file (share a small sample)? What output are you looking for from it? Commented Apr 28, 2017 at 5:55
  • @gurvinder372 I can't post a snippet right now, but the file is JS code. I'm trying to replace the array name and index (ex: arr[0]), with the actual value of it (ex: "value"). Commented Apr 28, 2017 at 5:59

1 Answer 1

1

A simple idea would be having arrays in current scope and use target javascript file content as input string for replace() method:

var arr = ['hello', 'my', 'world']
var str = `
var arr = ['hello', 'my', 'world']
console.log('arr[2]')
console.log('arr[0]')
console.log('arr[1]')
`
console.log(str.replace(/\b(\w+)\[(\d+)]/g, function(match, $p1, $p2) {
   return window[$p1][$p2];
}))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.