parse multiple levels of document.write nesting - javascript

The question is a bit weird, but I am trying this just for learning purpose.
I have this string
var str = "document.write('<script>document.write(\"<script>document.write('<script>document.write(\"Hello World\");<\/script>');<\/script>\");<\/script>')";
And, I am trying to parse/eval this string so that the inner most document.write prints "Hello World". Here's what I tried.
function (str) {
str = str.replace(/["']/g, '"')
.replace(/"<script>document.write/g, "")
.replace(/;<\/script\>"/g, "");
eval(str);
}
But, this looks like horrible cheating. I want to do it a more subtle way. for example escaping the \s or splitting </script> tags. But can't just simply escape backslashes, as the number of slashes would need to be more for deeper nesting.
Any ideas?

Related

String.replace with special characters noting working

I have spent several hours trying to figure out what is going on here looking at stack overflow and elsewhere and I cannot figure out what is going on. I would really appreciate any help!!
I need to make document.write('< /div>'); go to -> < /div>
I've simplified it down to the simplest possible case with the html example below.
<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>
Exclude the quotes and it works. It is being interpreted as a string literal because of the quotes, whereas a regular expression literal is expressed between plain /s.
Also, . needs to be escaped or it matches any other single character.
<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>
String.prototype.replace() accepts either a string or a regex. If you are going with a string this should be:
var str = "document.write('</div>');";
str = str.replace("document.write","");
console.log(str);

Regex to change quoting style

In the text that I get, I want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like "aren’t". I want to use a String.replace() with a regular expression to do this..
E:g:
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/*regEx*/, "\""));
//should return → "I'm the cook," he said, "it's my job."
Now I know a regex that works for me, at least for the example text.
console.log(text.replace(/\B'/g, "\""));
However, I wonder if there is any other regex I can use to accomplish this. Just curious.
I noticed that the regular expression you provided doesn't replace single quotes in the beginning of the string. I came up with this one instead:
var str = "'Hello', - she said\n'Hi!' - he whispered\n";
console.log(str.replace(/\B'|'\B/g, "\""));

split string of chain functions with reg-exp

I looked around on StackOverflow but could not find the answer!
Anyway, I was wondering how do I get following in JavaScript with regexp.
I have a string
bla().func1($(ele).attr("data")).func2.func3("test")... ;
and I want extract func1, func2, func3... from the given string, anybody have an example of how to do that?
Bear in mind, that the function names changes, so they are not func1, func2 ... they can be load, past, moon ... whatever
try this:
var str = 'bla().func1($(ele).attr("data")).func2("test")';
alert(str.split(/(?:\.)\w+\d+(?=\()/g));
There's the fiddle:
http://jsfiddle.net/cv6avhfb/3/
This code would split the string in parts while using as separators substrings like '.func1(', '.func2(', '.abc3(' and other. If the function names have different structure you just have to change the \w+\d+ part of the regex.
Here's the result of this code:
bla(),($(ele).attr("data")),("test")
And if you like to know more about regex in javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Repeatedly strip out innermost parenthesized expressions:
var str = 'bla().func1($(ele).attr("data")).func2.func3("test")... ';
var expression = /\([^(]*?\)/g;
while (expression.test(str)) { str = str.replace(expression, ''); }
document.write(str.split('.').slice(1).join(' '));
However, you shouldn't do this (why do you want to?). JS should be parsed by, well, JS parsers. For instance, the above will fail miserably if there's a string literal containing a parenthesis. You should parse this using Esprima and analyze the resulting parse tree.

JavaScript split().join() thousands separator replacement for .replace() for use on eBay

I use this for comma separated thousands on my site, works great...
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
I'm trying to implement a similar method for ebay using split().join(), since eBay have banned the usage of .replace(), any solution?
I tried using the same regx inside split(), but thus far it has not worked the same way.
Thanks.
maybe you can try to use search() to get the index of the string and remove the characters for the given index.
var pre_string = str.substing(0, found_index);
var post_string = str.substing(found_index + 3);
var replaced_string = pre_string + post_string;
("100,00,0").split(',').join(''); //"100000"
Something like this?
parseInt( ("100,00,0").split(',').join('') ,10); //100000
I think you are referring to:
Javascript .Replace Alternative
In there the code (by WereWolf - The Alpha) is:
String.prototype.fakeReplace=function(str, newstr) {
return this.split(str).join(newstr);
};
var str="Welcome javascript";
str=str.fakeReplace('javascript', '');
alert(str); // Welcome
So, your:
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Becomes:
str.myReplace(/\B(?=(\d{3})+(?!\d))/g, ",");
How?
because .split(STR) splits the string by STR (removing STR in process) into a two element array (or more), and rejoins it with .join(NEWSTR) which places NEWSTR inbetween the two strings in array.
"hello STR world" --.split(STR)--> ["hello "," world"] --.join(NEWSTR)--> "hello NEWSTR world"

Regex: match word (but delete commas after OR before)

I have tried to delete an item from a string divided with commas:
var str="this,is,unwanted,a,test";
if I do a simple str.replace('unwanted',''); I end up with 2 commas
if I do a more complex str.replace('unwanted','').replace(',,','');
It might work
But the problem comes when the str is like this:
var str="unwanted,this,is,a,test"; // or "...,unwanted"
However, I could do a 'if char at [0 or str.length] == comma', then remove it
But I really think this is not the way to go, it is absurd I need to do 2 replaces and 2 ifs to achieve what I want
I have heard that regex can do powerful stuff, but I simply can't understand it no matter how hard I try
Important Notes:
It should match after OR before (not both), or we will end with
"this,is,,a,test"
There are no spaces between commas
How about something less flaky than a regex for this sort of replacement?
str = str
.split(',')
.filter(function(token) { return token !== 'unwanted' })
.join(',');
jsFiddle.
However if you are convinced a regex is the best way...
str = str.replace(/(^|,)?unwanted(,|$)?/g, function(all, leading, trailing) {
return leading && trailing ? ',' : '';
});
(thanks Logan F. Smyth.)
jsFiddle.
Since Alex hasn't fixed this in his solution, I wanted to get a fully functional version up somewhere.
var unwanted = 'unwanted';
var regex = new RegExp('(^|,)' + unwanted + '(,|$)', 'g');
str = str.replace(regex, function(a, pre, suf) {
return pre && suf ? ',' : '';
});
The only thing to be careful of when dynamically building a regex, is that the 'unwanted' variable can't have anything in it that could be interpretted as a regex pattern.
There are way easier ways to parse this though, as Alex mentioned. Don't resort to regular expressions unless you have to.

Categories

Resources