/    Sign up×
Community /Pin to ProfileBookmark

Replace a string in <script> tags and execute

Hi,
I need a bit help, in the code below I an trying to replace a string with another string, then write the new string in JavaScript tags. But the result is not what I wanted: first the original string was not replaced, second plain text is shown, instead of popping up an alert. Is there a way I can replace the string and execute the command?
Any help is appreciated!

[CODE]<html>
<body>

<script type=”text/javascript”>

var str=”alert(“sometext”)”;

str.replace(“alert(“sometext”)”,”alert(“some new text”);” );

</script>

<script type=”text/javascript”>
document.write(str);
</script>
</body>
</html>
[/CODE]

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@mrhooJul 16.2011 — First, you need to set str=str.replace(whatever);

and second, a string is not executable code.

<!doctype html>

<html lang="en">

<head>

<title>Test Page</title>

</head>

<body>

<script>

var str="alert('sometext')";

str= str.replace("alert('sometext')","alert('some new text');" );

</script>

<script type="text/javascript">

eval(str);

</script>

</body>

</html>
×

Success!

Help @calnastic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...