Asperger
Asperger

Reputation: 3222

Looping through a word inside a script itself and changing it

I wonder if it is possible to replace all instances of a word in javascript. Say for instance I want to replace all instances of "function" with fn. I know doing so renders my function useless but this is just to give an example.

So my trouble is, 1. how do I access text within the script itself? Script traversing, similar to how we travel the node tree.

2. I assume such action comes with security risks, is that right?

Say you have a script like this:

var x = function () {

    function y () {
       // ...
    }

}

Upvotes: 1

Views: 47

Answers (2)

Charlie
Charlie

Reputation: 23798

You can do this by using eval

Look at this:

myScript = "myFunc = function foo() {console.log(9999)}";
eval(myScript);

Now you can run the function through myFunc()

It gets interesting here.

Change the name foo in your myScript to bar and the number to 0000

myScript = myScript.replace("foo", "bar");
myScript = myScript.replace("9999", "0000");
eval(myScript);
myFunc();

The function bar executes and prints 0000

There are lot of other ways you can do this. You can use JQuery getScript, for example, and be little creative to go a long way in this direction.


UPDATE

Taking the answer bit further...

There is a specific reason why I wanted to use the variable myFunc

To understand, run the following snippet

myScript = "function foo() {console.log(9999)}";
eval(myScript);
myScript = "function bar() {console.log(0000)}";
eval(myScript);

foo();
bar();

Now guess the reason why I used myFunc

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

You can access a script element like any other element. However, it will contain only one text node, which is the script itself.

You can do a replace on the text node like this:

var x = function () {
  console.log('I still work!');
    function y () {
       // ...
    }

}

var script= document.getElementsByTagName('script')[0];
script.textContent= script.textContent.replace(/function/g, 'fn');
document.querySelector('pre').textContent= script.textContent.trim();
x(); //I still work!
<pre></pre>

Note that changing the text note does not necessarily affect the functionality of the script.

Upvotes: 0

Related Questions