简体   繁体   中英

javascript regular expression to extract the code returned by content.html() in a string

I have a few javascript statements that I need to store in order to implement later in an undo/redo mechanism.

My statements consist of setting the HTML of the content div, and editing the global variable i . $('#content') can consist of many divs within it, each with their own inline style attributes. I was previously storing the multiple statements like this:

storedcontent = $('#content').html();
statements = "$('#content').html("+storedcontent+"); i = " +i+ "; ";

and then I would using eval(str); , when the undo button was pressed. An example of what might be stored in the statements variable is this:

content.html('<div id="left" class="margin-line" style="top: 15px; left: 15px; width:1px; height: 317px; border-right:1px dotted gray;"></div>     <div id="top" class="margin-line" style="top: 14px; left: 16px; height:1px; width: 569px; border-bottom:1px dotted gray; "></div>'); 
i = 3;

(Notice that after the .html() statement there's a variable assignment).

So what I was doing earlier was simply doing eval(statements) , in order to execute both the .html() and the i=3 statements.

But I've realized eval() had problems. So while retaining the two (and there could more) javascript statements in the statements variable, I just want to extract whatever comes between the brackets in $('#content').html() .

So I want a regex to extract from the variable statements , only whatever's returned by $('#content').html() , ie whatever I had in storedcontent . That way, instead of using eval, I can directly do $('#content').html(storedcontent);

I know I could easily use substring but I would like to know how to do it using regular expressions.

I've tried to edit the question but I think it might still be confusing. To simplify, perhaps I'm just asking, how, using regex, can we capture the string between two different substrings, in this case $('#content').html( and ); ?

I don't really understand why you're not using storedcontent but anyway.

What is inside the 'i' variable? If it's an integer, then the RegExp should be:

var storedcontent2 = statements.match(/#content\'\)\.html\((.*)(\);\s*i\s*=\s*\d+\s*;\s*)$/)[1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM