Web tricks - Useful Javascript

Here we will see some small JavaScript functions that may be quite useful.

Log a message

Who, among those ever developped in a programming language, never used a printf or some awful method to debug their code?
I thought so... Indeed, it is bad, but you must admit that it is quite easy and simple to use.
If you agree with me, you should like the following function:

/**
 * Simple function to log a message.
 * 
 * If there is no console, this function will display the message in an alert 
 * box.
 * 
 * @param message Message to log.
 */
function log(message) {
	if (typeof console !== 'undefined')
		console.log(message);
	else
		alert(message);
}

I wish to thank Loïc Yon for giving me this quite sympathic function (^_^).

Redirect the user

It is quite frequent to encounter a «temporary» webpage that will redirect you to another page after a few seconds.
Well, here is how to proceed through JavaScript:

/**
 * Function to redirect the browser.
 * 
 * If no redirection URL is passed, the function will simply reload the current page.
 * 
 * @param redirection URL for redirection.
 * @param delay (Optional) Delay in milliseconds before redirection.
 */
function redirect(redirection, delay) {
	if (redirection != null) {
		if (delay != null)
			setTimeout("window.document.location = '"+redirection+"'", delay);
		else
			window.document.location = redirection;
	}
	else
		window.document.reload();
}

Managing Strings

We use strings everywhere in programming language, and JavaScript is no exception to it. However, functions to manage strings, like trimming it or testing prefix/suffix, were not always present on all browsers.
If you are concerned about cross browsers/versions compatibility, you can always use the following functions:

/**
 * Function to test if a string ends with another string or not.
 * 
 * @see StackOverflow: endsWith in javascript
 * 
 * @param str String to test.
 * @param suffix Suffix to test if present at the end.
 * @return true if str ends with suffix, false if not.
 */
function strEndsWith(str, suffix) {
    return typeof str.endsWith !== 'undefined' ? str.endsWith(suffix) : str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/**
 * Function to test if a string starts with another string or not.
 * 
 * @param str String to test.
 * @param prefix Prefix to test if present at the start.
 * @return true if str starts with prefix, false if not.
 */
function strStartsWith(str, prefix) {
    return typeof str.startsWith !== 'undefined' ? str.startsWith(prefix) : str.indexOf(prefix, 0) == 0;
}

/**
 * Function to test if a string starts with another string or not.
 * 
 * @param str String to test.
 * @param prefix Prefix to test if present at the start.
 * @return true if str starts with prefix, false if not.
 */
function strTrim(str) {
    return typeof str.trim !== 'undefined' ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
Sections
Back to top