Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Wednesday, October 13, 2010

Some handy Javascript array methods

Working with javascript arrays today, I found some handy functions:

- Creating an array :
var ray = [];

- Joining two arrays :
var resultArray = ArrayOne.concat(ArrayTwo);

- Getting only unique items in an array :
(Jquery has a unique function, but it does not work on strings / numbers)
Array.prototype.unique = function() {
var result = new Array();
o: for (var i = 0, n = this.length; i < n; i++) {
for (var x = 0, y = result.length; x < y; x++) {
if (result[x] == this[i]) {
continue o;
}
}
result[result.length] = this[i];
}
return r;
}


- For each in JavaScript(using JQuery):
(although JavaScript has for (item in collection) functionality, it is not useful as it also iterates through the methods of the object.)
$.each(collection, function(index, value) { alert(index + ' : ' + value); });




- Bonus JavaScript : Splitting a string by multiple delimiters :
use a regular expression :
var result = myString.split(/[DELIMITERS]+/);
just replace DELIMITERS with the delimiters you want (one character delimiters)

Thursday, July 2, 2009

Javascipt Replace, Replace All

Working in javascript today,
I found out that in javascript, the replace function only replaces the first occurrence, not all as in c#/VB.
You can test this by pasting the following in the addressbar of (most) browsers:

javascript:alert('test-test-test'.replace('-',''));

To replace all occurrences you need to use regular expression (place the word you want to find between / /g :

javascript:alert('test-test-test'.replace(/-/g,''));


or you can create a javascript function eg:

function replaceAll(text, findText, replaceText)
{
return text.replace( new RegExp(findText,"g"), replaceText);
}

Wednesday, October 8, 2008

Window opened from javascript

When using javascript to open a window, it appears on top.
When this window loses focus (gets in the background),
and the user clicks the link again, the window is reloaded,
but does not get the focus again.

Since for some people this is important, the solution is to make sure the opened window has the focus :

var openedWindow = window.open("someurl", "somewindowname");
openedWindow.focus();


This will refocus the opened window.