christopher
christopher

Reputation: 27356

Odd Javascript String manipulation behaviour

I'm not a Javascript expert, but I'm starting to think this is somewhat strange! Essentially, I'd written this function:

 function onChange()
 {
      if(this.responseText.length != 0) {

       // Get the new HTML Page requested from the servlet.
       var currentHTML = new XMLSerializer().serializeToString(document);
       var newHTML = this.responseText;

       currentHTML = currentHTML.replace('/\s+/g','');
       currentHTML = currentHTML.replace('/[\n\r]/g','');
       currentHTML = currentHTML.replace('/\t/g','');

       newHTML = newHTML.replace('/\s+/g','');
       newHTML = newHTML.replace('/[\n\r]/g','');
       newHTML = newHTML.replace('/\t/g','');


       // (There's also some alerts here just to get the output)
 }

Now, when the function obtains values for currentHTML and newHTML, it's passing them through the regex methods, that are designed to strip out all the spaces, carriage returns and tabs. However, this is not happening. No errors, no faults. Passing through and it's not changing the variables in the slightest.

Upvotes: 1

Views: 73

Answers (2)

Mohammad Ismail Khan
Mohammad Ismail Khan

Reputation: 651

I think you have forget to close if body.

function onChange()

{ if(this.responseText.length != 0) {

   // Get the new HTML Page requested from the servlet.
   var currentHTML = new XMLSerializer().serializeToString(document);
   var newHTML = this.responseText;

   currentHTML = currentHTML.replace('/\s+/g','');
   currentHTML = currentHTML.replace('/[\n\r]/g','');
   currentHTML = currentHTML.replace('/\t/g','');

   newHTML = newHTML.replace('/\s+/g','');
   newHTML = newHTML.replace('/[\n\r]/g','');
   newHTML = newHTML.replace('/\t/g','');

   }
   // (There's also some alerts here just to get the output)

}

Upvotes: 1

Blender
Blender

Reputation: 298582

Regex literals aren't surrounded by quotes. You need to change this:

currentHTML.replace('/\s+/g','');

To this:

currentHTML.replace(/\s+/g,'');

Also, your replacements are a little redundant. \s already matches tabs and newlines (along with spaces!).

Upvotes: 5

Related Questions