SharePoint with Javascript question

IndyColtsFan

Lifer
Sep 22, 2007
33,656
687
126
So, I have a question regarding a problem I'm trying to solve in SharePoint. I need any link containing a doc, docx, xls, xlsx, ppt, pptx, and pdf file to open in a new tab. I've got the code below inserted into my masterpage, but it doesn't seem to work. Note that if I take out the IF statement, ALL links on the site open in a new tab. I ONLY need links containing the extensions above to open in a new tab.


<script language="JavaScript">
_spBodyOnLoadFunctionNames.push("rewriteLinks");


function rewriteLinks() {
//create an array to store all
var anchors = document.getElementsByTagName("a");
var regex = /\.(doc|xls|ppt|pdf)$/g;

//loop through the array
for (var x=0; x<anchors.length; x++) {
//add the [target] attribute and rewrite the [href] attribute
if (regex.test(anchors[x].href)) {
anchors[x].target = "_blank";
}
}
}
</script>

I'm hoping I just have a simple error in the code above. Anyone?