开发者

Javascript .replace() / regex with code as string

I'm trying to "remove" (just replace it with "") the following String:

<script type="text/javascript">
document.createElement("img").src="http://www.google.com"
</script>

From the following String:

<SCRIPT LANGUAGE=JavaScript>
var PAswf = "_ADPATH_[%SWF File%]";
var advurl = "_ADCLICK_";
var PAadvurl = escape(advurl);
var PAwidth = "[%Width%]";
var PAheight = "[%Height%]";
var wmValue = "_ADDCP(wm)_";
if (!wmValue)wmValue = "opaque";
var PAwmode = wmVal开发者_StackOverflow中文版ue;
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' WIDTH="'+ PAwidth +'" HEIGHT="'+ PAheight +'">');
document.write('<PARAM NAME=movie VAL'+'UE="' + PAswf + '?clickTag='+ PAadvurl +'"><PARAM NAME=quality VALUE=high><PARAM NAME=wmode VALUE='+ PAwmode +'>');
document.write('<EMBED sr'+'c="'+PAswf + '?clickTag='+ PAadvurl +'" quality=high wmode='+ PAwmode);
document.write(' swLiveConnect=TRUE WIDTH="'+ PAwidth +'" HEIGHT="'+ PAheight +'"');
document.write(' TYPE="application/x-shockwave-flash">');
document.write('</EMBED></OBJECT>');
</SCRIPT>
<script type="text/javascript">
document.createElement("img").src="http://www.google.com"
</script>

As you can see, the String is at the bottom of the code block, but that shouldn't really matter. I've stored the first string as a variable, codeString, and tried the following.

// code refers to the bigger code string
code.replace(/codeString/gm, "");

Doesn't seem to match. I'm sure I'm doing something wildly wrong, but I've searched for about an hour and have come up empty. Any ideas?


/codeString/ is a regular expression searching for the literal "codeString", not a variable containing a pattern. Also, string.replace(pattern, replacement) does not modify string but returns a new string with the replacement applied.

You do not need a regular expression for stripping fixed strings like this, the next code will remove the string once from code:

var codeString = '<script type="text/javascript">\n' +
    'document.createElement("img").src="http://www.google.com"\n' +
    '<\/script>';
code = code.replace(codeString, "");


Well you can start with

code.replace(codestring, "");

If it needs to be a regular expression, you can use:

code.replace(new RegExp(codestring, "gm"), "");

but be aware that the regex metacharacters should be escaped with backslashes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜