Javascript regex not working in IE - javascript

So I've got this table being generated and each cell is given a unique id which is r#c# where the # is the row/column. I've got the code below that extracts the row number and column number from the ID of the cell on mouseover, and it works just fine in firefox and chrome, but does not work in internet explorer.
var cell_id = $(this).attr("id");
var matches = /[a-z]+(\d+)[a-z]+(\d+)/(cell_id);
var row = matches[1];
var col = matches[2];
Why doesn't this work in explorer?

In Internet Explorer, a regex cannot be used as a function. The equivalent is the exec() method, which is implemented cross browser.
var matches = /[a-z]+(\d+)[a-z]+(\d+)/.exec(cell_id);
Felt that this answer was a little incomplete without mentioning that Internet Explorer isn't the only browser that doesn't allow a regular expression to be executed like a function. In fact, it's a Mozilla extension and it's not even defined in the ECMAScript 3rd or 5th editions. You can easily check to see if it's supported using the typeof operator:
if (typeof / / == "function")
// Regex can be used like a function
else if (typeof / / == "object")
// Regex cannot be used like a function
I don't really understand why this was even implemented or why you'd even want to check for it, it's best to just err on the side of caution and use the exec method.

Related

Does Firefox browser not recognize table.cells?

I have the following JavaScript code.
var myCellCollection = document.getElementById('myTbl').cells;
This works well in IE and it returns a collection of table cells. But the same line returns "undefined" in Firefox. I am using IE 9 and Firefox 12.
You should use document.getElementById("myTbl").getElementsByTagName('td');
Stumbled into this today whilst porting an older Internet Explorer app.
Warning:
container.getElementsByTagName('tagname') returns ALL the elements inside container that matches the query tagname.
Thus table.getElementsByTagName('td') will return all td's including those of nested tables!
However table.cells doesn't do that (where implemented).
Also, obviously, it won't match th. So those cells are not in returned collection, optionally leading to the 'problem' of how to resolve their order relative to the td's...
To shim the expected functionality of table.cells (returning both th and td in DOM-order), I wrote the following simple function:
function tableCells(t){
if(t.cells) return t.cells; // use internal routine when supported
for(var a=[], r=t.rows, y=0, c, x; t=r[y++];){
for(c=t.cells, x=0; t=c[x++]; a.push(t));
}
return a;
}
Alternatively, using 'single return' by 'if-else' packs to the same size exactly, yet the above gzips smaller. PS: I tried concat-ting the table.rows[X].cells, but that didn't work (although I wouldn't feel safe doing so anyways)
Usage example:
var identifier = tableCells( /*reference to table (or thead/tbody/tfoot) here*/ );
It will return an array (not a live collection) like the result from table.cells.
Hope this helps someone

How to remove linebreaks in IE with Javascript?

I am trying to remove linebreaks with JavaScript. It works in all browsers except Internet Explorer (tested in ie7, ie8). I have read a lot of posts but couldn't find a solution to the problem.
Var someText = "Here’s your text.\n It has line breaks that need to be removed.\rUsing Javascript.\r\n";
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
What else can I try?
* EDITED *****
Here's more code and a better explanation of my problem:
function checkLength(fn) {
var fn = document.getElementById(fn);
var fnb = fn.value;
var fnb = fnb.replace(/(\r\n|\n|\r)/gm,"");
var len = fnb.length;
...
What I am trying to do is calculate the number of chars in a textarea. I had to calculate with both Javascript and PHP and because of the linebreaks, PHP and Javascript never came to the same number. When removing the linebreaks, it is all good except in Internet Explorer (when I calculate it with Javascript). fnb.replace doesn't change anything in Internet Explorer for the character count so that is why I am sure it does not remove the linebreaks correctly. In all other browsers it is fine, I can see the difference in the counter after removing the linebreaks in javascript. Only in ie it doesn't change a thing. I have tried a couple of things as well as your suggestions below and the char count before removing the linebreaks and after is the same in ie.
///////// MY ANSWER /////////////////////////////////////
function checkLength(fn) {
var fn = document.getElementById(fn);
var fnb = fn.value;
var fnb = fnb.replace(/(\r\n|\n|\r)/gm,"");
var len = fnb.length;
...
Like Tomalak said, my logic could be improved - Sorry for being new to JavaScript & programming. Maybe Tomalak doesn't make any mistakes but I'm sure everyone else does. We have to make mistakes to learn.
Internet Explorer didn't like
var fn = document.getElementById(fn);
var fnb = fn.value;
I had to change it to:
var fnb = document.getElementById(fn).value;
Even if it wasn't logical, it should have worked. It did work in all browsers except ie. It's a bug.
That was the answer I was looking for.
Try this:
someText = someText.replace(/[\r\n]+/gm,"");
In fact, the regular expression works just fine in at least IE8.0.
The real problem is that you wrote Var instead of var; Firefox lets you get away with it, but IE doesn't.
You don't need the m flag, but you ought to replace with a space instead of nothing.
someText = someText.replace(/[\r\n]+/g,' ');

Why does Internet Explorer not like this jQuery?

While debugging some jQuery that is not working in IE, I found this error message:
var item = $("#item_"+ itemArray[itemIndex]).find('a').text().trim();
Object doesn't support this property or method (script.js, line 100, character 2)
The character 2 doesn't make sense to me. Based on the text displayed character 2 would be the letter a in var but of course that doesn't make any sense.
(Should I not use var?)
I know that jQuery is working to some extent or the script would not have been able to get this far on my page.
IE doesn't have String.trim(), you'll need $.trim() (which uses native trim if available, emulates it in IE), like this:
var item = $.trim($("#item_"+ itemArray[itemIndex]).find('a').text());
IE doesn't have a trim method.
Instead, you can call jQuery.trim(...).

A weird regex problem

The following code results in "undefined" for lastIndex:
var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);
document.write(r.lastIndex);
However, it works perfectly for r.index (and r.input).
I am using Firefox. Does anybody have a clue?
EDIT: OK, the above code works perfectly in IE! Further, in Firefox, it works perfectly if instead of calling r.lastIndex on line 5, a.lastIndex is called. It appears that Firefox does not return lastIndex property in the result - rather sets the property for the pattern invoking the exec() only. Interesting that IE sets both.
This is one of those places where Microsoft decided to add some stuff to the language and act as if it was supposed to be there. Thankfully, they are now cleaning up their act and documenting such nonsense.
To be clear: Firefox is correct according to the ECMAScript Language Specification 3rd Edition (PDF, 705KB).
IE is not correct; its behaviour is a proprietary extension. There is no reason to believe that this IE-specific behaviour will ever be supported by any other browser. It certainly isn't at the moment. See JScript Deviations from ES3 (PDF, 580KB, by Pratap Lakshman of Microsoft Corporation) Section 4.6 for more on this particular deviation from the spec, including tests showing no support on other browsers.
Note also that this may not even be supported in the future by IE: a number of proprietary IE CSS-related mechanisms are disabled by default on IE8-in-IE8-mode, and future implementations of JScript may find a reason to similarly disable this extension to the language.
lastIndex is a property of a RegExp object. So try this:
a.lastIndex
To avoid all the weird, try this
var a = /cat/g;
var l = "A test sentence containing cat and dog.";
var r = a.exec(l);
var lastIndex = (r!=null) ? l.indexOf(r[0])+r[0].length : 0;
It is used here: http://www.pagecolumn.com/tool/regtest.htm

childNodes not working in Firefox and Chrome but working in IE

I have a gridview in its 3rd cell, there is textbox control, I am calling javascript function on onchange.
Can some body tell me why this is not working in Firefox and Chrome but working in IE
grd.rows[rowindex].cells[3].childNodes[0].value
It return correct value in IE but not in Chrome and firefox (In FF and Chrome it return undefined)?
Please also suggest me solution to handle this problem.
Edit
alert(grd.rows[ri].cells[3].childNodes[0].value);//IE value=correct value, FF and chrome value=undfined
alert(grd.rows[ri].cells[3].childNodes[1].value);//IE value=undfined, FF and Chrome value= correct value
Thanks
I believe that this is because IE ignores text nodes that only contain newlines and tabs. Personally I prefer they be ignored but I would rather have consistency across the browsers.
<p><!-- This comment represents a text node.
--><em>text</em>
</p>
Try out this. I have same problem and this problem is resolved by just replace "childNodes" with "children"
alert(grd.rows[ri].cells[3].children[0].value);
try
grd.rows[rowindex].cells[3].childNodes[1].value
or the best, look at table in integrated Developer tool
#ChaosPandion:
Hey friend don't use this type of check for childNodes.
The counting of childNodes varies. Some browsers include empty textNodes, some do not. In this sort of operation as I believe you are describing, it is better to use the parent's getElementsByTagName() method. That way the number of chidren and index of each child you are looking for will be consistent.
OR
just check your browser's name.
if it is IE then as it neglects empty textnode, the childNode in it is less by one number than other browsers.
for eg.
var isIE = navigator.appName;
if (isIE == "Microsoft Internet Explorer") {
var removeProductID = document.getElementById(obj.childNodes[0].id).getAttribute("abc");
}
else {
var removeProductID = document.getElementById(obj.childNodes[1].id).getAttribute("abc");
}
Hope this helps. Enjoy coding.
If you are looking for the text, use grd.rows[rowindex].cells[3].childNodes[0].data for non-IE browsers.
Getting text value of an Element Node
var oCell = grd.rows[rowindex].cells[3];
alert(oCell.textContent || oCell.innerText)
Getting text value of a Text Node (less safe compared to previous)
var oText = grd.rows[rowindex].cells[3].childNodes[0];
alert(oCell.data || oCell.value)
As ChaosPandion says, IE ignores white-space text-nodes. The following should work cross-browser:
var cell = grd.rows[rowindex].cells[3];
for (var textbox=cell.firstChild; textbox.nodeType!==1; textbox=textbox.nextSibling);
alert(textbox.value);
However, you say you are calling the function on onchange.
Presumably that means the onchange event for the textbox in question.
In that case the event argument in your event handler should have a pointer to the textbox.
Look at the target or srcElement property. e.g.
function onChange(e) {
e = e || window.event;
var textbox = e.target || e.srcElement;
alert(textbox.value);
}
try getElementsByTagName() instead of ChildNodes. it will be working for FF , chrome and for IE as well.

Categories