9

Super newbie at Javascript here. I have a problem with whitespace that I'm hoping someone can help me with.

I have a function that looks like this:

function createLinks()  
  {
  var i = 0;
  tbody = document.getElementsByTagName('tbody')[3];
    console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,''))
  trs = tbody.getElementsByTagName('tr');
console.log('trs.length = '+trs.length);
  for (i=0;i<trs.length;i++)
  {
orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'');
    console.log('order: '+orderId);

hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17';
linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>';
    console.log(linkReturn);

trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn;

  }
}

I call this function using another function when the page is initially loaded. This works perfectly.

However, I also call this function in another way when data on the page changes. There's a dropdown list that I have an onClick attribute attached to. That onClick event calls the first function, which in turn calls the second function (above). Both of these functions are saved into text variables and appended to the document, as below:

var scriptTextLinks = " function createLinksText()  {  var i = 0;  tbody = document.getElementsByTagName('tbody')[3];   console.log('test order ID: '+document.getElementsByTagName('tbody')[3].getElementsByTagName('tr')[0].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,''));  trs = tbody.getElementsByTagName('tr'); console.log('trs.length = '+trs.length);  for (i=0;i<trs.length;i++)      { orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId); hrefReturn = 'https://www.example.com/example.html?view=search&range=all&orderId='+orderId+'+&x=13&y=17'; linkReturn = '<a href='+hrefReturn+'>'+orderId+'</a>';        console.log(linkReturn);    trs[i].getElementsByTagName('td')[1].innerHTML = linkReturn;   }  console.log('complete'); } "

Finally, here is the specific problem. When THIS version of the same function is called by events on the webpage, it fails to properly delete the whitespace, which breaks the link that it's supposed to create.

This is the exact problem section of code:

orderId = trs[i].getElementsByTagName('td')[1].textContent.replace(/^\s+|\s+$/g,'').replace(/\s/g,''); orderId = orderId.replace(/\s/g,''); console.log('order: '+orderId);

So instead of storing the variable like it should, like this:

"XXXXXXXXX"

It is stored like this:

"   
      XXXXXXXXXX
                  "

Which, again, kills the link.

Can anybody clarify what's going on here, and how I can fix it? Thanks in advance!

raspberry_door
  • 199
  • 1
  • 2
  • 11
  • 1
    HIya - it will be good if you can jsfiddle it **or** this might help http://stackoverflow.com/questions/360491/how-do-i-strip-white-space-when-grabbing-text-with-jquery cheers, – Tats_innit Mar 15 '12 at 22:34

1 Answers1

18

To strip all that surrounding whitespace you can use the standard .trim() method.

var myString = "                \n               XXXXXXX           \n         ";
myString = myString.trim();

You can strip all leading and trailing, and compress internal whitespace to a single space, as is normally done in HTML rendering, like this...

var myString = "    \n    XXXX  \n     YYYY    \n   ";
myString = myString.replace(/\s+/g, " ").trim();

Also, see tharrison's comment below.

(though my /\s+/g pattern worked fine with the embedded \n newlines)


Cure for IE<9

"shim.js"

(function() {
    if (! String.prototype.trim) {
        //alert("No 'trim()' method. Adding it.");
        String.prototype.trim = function() {
            return this.replace(/^\s+|\s+$/mg, '');
        };
    }
})();

(Or, if you might want to do other things in your shim...)

var shim = {
    init: function() {
        if (! String.prototype.trim) {
            String.prototype.trim = function() {
                return this.replace(/^\s+|\s+$/mg, '');
            };
        }
    }
};
shim.init();

Your HTML file

<script type="text/javascript" src="shim.js"></script>
Stephen P
  • 14,422
  • 2
  • 43
  • 67
  • 2
    As an alternative, add the "m" flag to have the pattern span multiple lines, like ...`.replace(/^\s+|\s+$/gm,'');` – Tom Harrison Mar 15 '12 at 22:39
  • 2
    Worthy of note; `trim()` is only standard in ES5, and isn't supported in IE < 9. – Matt Mar 15 '12 at 22:41
  • @Matt - yes, *aaauugh!* I rarely think of IE's limitations as I'm in a position where I can require browser upgrades and/or refuse to support non-conforming browsers. – Stephen P Mar 15 '12 at 22:48
  • @StephenP: I'm jealous of you ;) – Matt Mar 15 '12 at 22:48