Super new to Javascript here. I have a problem with spaces that I hope someone can help me.
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. It works great.
However, I also call this function differently when the data on the page changes. There is a drop-down list to which I attached the onClick attribute. This onClick event calls the first function, which in turn calls the second function (see above). Both of these functions are stored in text variables and added to the document, as shown 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 a web page, it cannot correctly remove spaces, which breaks the connection that it must create.
This is the exact section of code issues:
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 a variable, as it should be, like this:
"XXXXXXXXX"
It is saved as follows:
" XXXXXXXXXX "
Which, again, kills the link.
Can anyone explain what is going on here and how can I fix it? Thanks in advance!