Why string replace fails?

D

Don Li

Hi,

The blank.html reads:
<html><body bgcolor="#FFFFFF"></body></html>

// function
var str = new String();
str.replace('<html><body bgcolor="#FFFFFF"></body></
html>','<html><head><title></title></head><body
bgcolor=##FFFFFF><p>Hello 1</p></body></html>');
document.location = 'blank.html';

Thanks.

P.S.
If I use a new Object instead of String, but then we don't have the
{replace} method.
 
T

Thomas 'PointedEars' Lahn

Don said:
The blank.html reads:
<html><body bgcolor="#FFFFFF"></body></html>

// function
var str = new String();
str.replace('<html><body bgcolor="#FFFFFF"></body></
html>','<html><head><title></title></head><body
bgcolor=##FFFFFF><p>Hello 1</p></body></html>');
document.location = 'blank.html';

To answer your question: because you are using fantasy syntax, to say the
least. The String.prototype.replace() method requires two arguments, the
first being the substring or Regular Expression to match, and the second
being the replacement string or a reference to a Function object that
returns it.

Since

var str = new String();

is roughly equivalent to

var str = "";

with

str.replace('...', '...');

there is never a match.

Maybe you were looking for

document.documentElement.innerHTML =
document.documentElement.innerHTML.replace(...);

but that is awfully bad style, not least because the markup is invalid.
You want to append a `p' element instead:

var p = document.createElement("p");
var txt = document.createTextNode("Hello 1");
p.appendChild(txt);
document.body.appendChild(p);

Your document.location assignment does not make any sense either because, if
it even works, it overwrites the changes you did before. RTFM.
P.S.
If I use a new Object instead of String, but then we don't have the
{replace} method.

You don't say.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,143
Messages
2,570,822
Members
47,368
Latest member
michaelsmithh

Latest Threads

Top