转载自: http://viralpatel.net/blogs/javascript-tips-tricks/
If you are doing lot of JavaScript programming, you might find below list of code snippets very useful. Keep it handy (bookmark it) and save it for future reference.
Here are 20 very useful JavaScript tips and tricks for you.
Disclaimer: Not all these snippet are written by me. Some of them are collected from other sources on Internet.
1. Converting JavaScript Array to CSV
First one goes like this. You have a javascript array of strings (or numbers) and you want to convert it to comma separated values (csv). We’ll below is the code snippet:
Reference: Array to CSV in JavaScript
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ];
var str = fruits.valueOf();
//print str: apple,peaches,oranges,mangoes |
The valueOf()
method will convert an array in javascript to a comma separated string.
Now what if you want to use pipe (|) as delimeter instead of comma. You can convert a js array into a delimeted string using join()
method. See below:
var fruits = [ 'apple' , 'peaches' , 'oranges' , 'mangoes' ];
var str = fruits.join( "|" );
//print str: apple|peaches|oranges|mangoes |
The join()
method will convert the array into a pipe separated string.
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/1.html" frameborder="0" width="100%" height="200px"></iframe>
2. Convert CSV to Array in JavaScript
Now what if you want to convert a comma seprated string into a JavaScript array? We’ll there is a method for that too. You can use split()
method to split a string using any token (for instance comma) and create an array.
Reference: Array to CSV in JavaScript
In below example we split string str
on comma (,) and create a fruitsArray
array.
var str = "apple, peaches, oranges, mangoes" ;
var fruitsArray = str.split( "," );
//print fruitsArray[0]: apple |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/2.html" frameborder="0" width="100%" height="200px"></iframe>
3. Remove Array element by Index
You have an array. You want to remove a perticular element from array based on its index. We’ll you can do so using splice()
method. This method can add as well as removes element from an array. We will stick to its removal usage.
Reference: Remove element by array index
function removeByIndex(arr, index) {
arr.splice(index, 1);
} test = new Array();
test[0] = 'Apple' ;
test[1] = 'Ball' ;
test[2] = 'Cat' ;
test[3] = 'Dog' ;
alert( "Array before removing elements: " +test);
removeByIndex(test, 2); alert( "Array after removing elements: " +test);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/3.html" frameborder="0" width="100%" height="200px"></iframe>
4. Remove Array element by Value
This one is very useful. You have an array and you want to remove an element based on its value (instead of index).
Reference: Remove element by array index
function removeByValue(arr, val) {
for ( var i=0; i<arr.length; i++) {
if (arr[i] == val) {
arr.splice(i, 1);
break ;
}
}
} var somearray = [ "mon" , "tue" , "wed" , "thur" ]
removeByValue(somearray, "tue" );
//somearray will now have "mon", "wed", "thur" |
See how in above code we defined a method removeByValue
that takes serves the purpose. In JavaScript you can define new functions to classes at runtime (although this is discourage) usingprototypes
.
In below code snippet, we create a new method removeByValue()
within Array
class. So now you can call this method as any other arrays method.
Array.prototype.removeByValue = function (val) {
for ( var i=0; i< this .length; i++) {
if ( this [i] == val) {
this .splice(i, 1);
break ;
}
}
} //.. var somearray = [ "mon" , "tue" , "wed" , "thur" ]
somearray.removeByValue( "tue" );
//somearray will now have "mon", "wed", "thur" |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/4.html" frameborder="0" width="100%" height="200px"></iframe>
5. Calling JavaScript function from String
Sometime you want to call a Javascript method at runtime whos name you know. Let say there is a method “foo()” which you want to call at runtime. Below is a small JS snippet that helps you calling a method just by its name.
Reference: Call Function as String
var strFun = "someFunction" ; //Name of the function to be called
var strParam = "this is the parameter" ; //Parameters to be passed in function
//Create the function var fn = window[strFun];
//Call the function fn(strParam); |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/5.html" frameborder="0" width="100%" height="200px"></iframe>
6. Generate Random number from 1 to N
Below little snippet helps you in generating random number between 1 to N. Might come handy for your next JS game.
//random number from 1 to N var random = Math.floor(Math.random() * N + 1);
//random number from 1 to 10 var random = Math.floor(Math.random() * 10 + 1);
//random number from 1 to 100 var random = Math.floor(Math.random() * 100 + 1);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/6.html" frameborder="0" width="100%" height="200px"></iframe>
7. Capture browser close button event or exiting the page in JavaScript
This is a common use case. You want to capture the browsers close event so that you can alert user if there is any unsaved data on webpage that should be saved. Below javascript snippet will help you in that.
Reference: Capture Browser Close Event
<script language= "javascript" >
function fnUnloadHandler() {
// Add your code here
alert( "Unload event.. Do something to invalidate users session.." );
} </script> <body onbeforeunload= "fnUnloadHandler()" >
<!-- Your page content -->
</body> |
8. Warn user if Back is pressed
This is same as above. Difference is instead of capturing close event here we capture back button event. So that we know if user is moving awaw from this webpage.
Reference: Capture Browser Back Button
window.onbeforeunload = function () {
return "You work will be lost." ;
}; |
9. Check if Form is Dirty
A common usecase. You need to check if user changed anything in an HTML form. Below functionformIsDirty
returns a boolean value true or false depending on weather user modified something within the form.
/** * Determines if a form is dirty by comparing the current value of each element
* with its default value.
*
* @param {Form} form the form to be checked.
* @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
* otherwise.
*/
function formIsDirty(form) {
for ( var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio" ) {
if (element.checked != element.defaultChecked) {
return true ;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea" ) {
if (element.value != element.defaultValue) {
return true ;
}
}
else if (type == "select-one" || type == "select-multiple" ) {
for ( var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true ;
}
}
}
}
return false ;
} |
window.onbeforeunload = function (e) {
e = e || window.event;
if (formIsDirty(document.forms[ "someForm" ])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes." ;
}
// For Safari
return "You have unsaved changes." ;
}
}; |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/8.html" frameborder="0" width="100%" height="200px"></iframe>
10. Disable Back button using JavaScript
This one is tricky. You want to disable the browsers back button (Dont ask me why!!). Below code snippet will let you do this. The only catch here is that you need to put this code in page where you dont want user to come back. See below reference for more details.
Reference: Disable Browsers Back Button
<SCRIPT type= "text/javascript" >
window.history.forward();
function noBack() { window.history.forward(); }
</SCRIPT> </HEAD> <BODY onload= "noBack();"
onpageshow= "if (event.persisted) noBack();" onunload= "" >
|
11. Deleting Multiple Values From Listbox in JavaScript
You have a SELECT box. User can select multiple OPTIONS from this SELECT box and remove them. Below Javascript function selectBoxRemove
let you do this. Just pass ID of SELECT object you want to remove OPTIONS in.
Reference: Delete Multiple Options in Select
function selectBoxRemove(sourceID) {
//get the listbox object from id.
var src = document.getElementById(sourceID);
//iterate through each option of the listbox
for ( var count= src.options.length-1; count >= 0; count--) {
//if the option is selected, delete the option
if (src.options[count].selected == true ) {
try {
src.remove(count, null );
} catch (error) {
src.remove(count);
}
}
}
} |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/11.html" frameborder="0" width="100%" height="260px"></iframe>
12. Listbox Select All/Deselect All using JavaScript
You can use below JS snippet to select/deselect all the OPTIONS from a SELECT box. Just pass the ID of select box you want to perform this operation on and also a boolean value isSelect
specifying what operation you want to perform.
Reference: Select All/None using Javascript
function listboxSelectDeselect(listID, isSelect) {
var listbox = document.getElementById(listID);
for ( var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
} |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/12.html" frameborder="0" width="100%" height="270px"></iframe>
13. Listbox Move selected items Up / Down
This one is useful if you are playing a lot with multi options select box in your application. This function let you move select OPTIONS in a SELECT box to UP or DOWN. See below reference for more details.
Reference: Move Up/Down Selected Items in a Listbox
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if (-1 == selIndex) {
alert( "Please select an option to move." );
return ;
}
var increment = -1;
if (direction == 'up' )
increment = -1;
else
increment = 1;
if ((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return ;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
} //.. //.. listbox_move( 'countryList' , 'up' ); //move up the selected option
listbox_move( 'countryList' , 'down' ); //move down the selected option
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/13.html" frameborder="0" width="100%" height="260px"></iframe>
14. Listbox Move Left/Right Options
This javascript function lets you move selected OPTIONS between two SELECT boxes. Check below reference for details.
Reference: Move Options Left/Right between two SELECT boxes
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for ( var count=0; count < src.options.length; count++) {
if (src.options[count].selected == true ) {
var option = src.options[count];
var newOption = document.createElement( "option" );
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true ;
try {
dest.add(newOption, null ); //Standard
src.remove(count, null );
} catch (error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
} //.. //.. listbox_moveacross( 'countryList' , 'selectedCountryList' );
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/14.html" frameborder="0" width="100%" height="260px"></iframe>
15. Initialize JavaScript Array with series of numbers
Sometime you want to initialize a Javascript array with series of numbers. Below code snippet will let you achieve this. This will initialiaze array numbers
with numbers 1 to 100.
var numbers = [];
for ( var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100] |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/15.html" frameborder="0" width="100%" height="200px"></iframe>
16. Rounding Numbers to ‘N’ Decimals
This one is quite useful. It will let you round off a number to ‘N’ decimal places. Here in below example we are rounding of a number to 2 decimal places.
var num = 2.443242342;
alert(num.toFixed(2)); // 2.44
|
Note that we use toFixed()
method here. toFixed(n)
provides n length after the decimal point; whereastoPrecision(x)
provides x total length.
num = 500.2349; result = num.toPrecision(4); // result will equal 500.2
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/16.html" frameborder="0" width="100%" height="200px"></iframe>
17. Check if String contains another substring in JavaScript
Below code snippet (courtesy Stackoverflow) let you check if a given string contains another substring.
Reference: stackoverflow
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for ( var i = (start || 0), j = this .length; i < j; i++) {
if ( this [i] === obj) { return i; }
}
return -1;
}
} if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~ this .indexOf(arg);
};
} |
The code will add two new methods to String, indexOf
and contains
. Once this is done, you can use contains method to check weather a substring is present in a given string.
var hay = "a quick brown fox jumps over lazy dog";
var needle = "jumps";
alert(hay.contains(needle));
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/17.html" frameborder="0" width="100%" height="200px"></iframe>
18. Remove Duplicates from JavaScript Array
Aha!! You know this one comes quite handy. Just call removeDuplicates method and pass the array, it should remove all duplicate elements from the array.
function removeDuplicates(arr) {
var temp = {};
for ( var i = 0; i < arr.length; i++)
temp[arr[i]] = true ;
var r = [];
for ( var k in temp)
r.push(k);
return r;
} //Usage var fruits = [ 'apple' , 'orange' , 'peach' , 'apple' , 'strawberry' , 'orange' ];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry']; |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/18.html" frameborder="0" width="100%" height="200px"></iframe>
19. Trim a String in JavaScript
Below code will add a method trim() to String which can be used to remove spaces from both sides of a string.
if (!String.prototype.trim) {
String.prototype.trim= function () {
return this .replace(/^\s+|\s+$/g, '' );
};
} //usage var str = " some string " ;
str.trim(); //print str = "some string" |
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/19.html" frameborder="0" width="100%" height="200px"></iframe>
20. Redirect webpage in JavaScript
This javascript code should perform http redirect on a given URL.
window.location.href = "http://viralpatel.net" ;
|
21. Encode a URL in JavaScript
Whenever you are making an http request and passing some parameters. You should encode the URL string. Use encodeURIComponent function for encoding a url parameter.
Reference: w3scools
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
|
<iframe style="font-size: 1em; outline: 0px; border-width: 0px; vertical-align: baseline; margin: 0px; padding: 0px;" src="http://viralpatel.net/blogs/demo/js/javascript-tips/21.html" frameborder="0" width="100%" height="200px"></iframe>
相关推荐
JavaScript是一种用于开发Internet客户端应用的基于事件的脚本语言,它也是一套与超文本标记语言HTML紧密结合的脚本语言,为网页制作者提供了非常灵活的应用和发挥空间。 本书用详尽的实例全面介绍了使用...
全书共分10篇,主要包括JavaScript的时间日期类、文本、鼠标、图片、页面等特效、页面技巧与页面游戏、导航菜单、Cookie和JavaScript的综合技巧等方面,涉及了JavaScript的网络应用的绝大部分内容。针对每个实例给出...
6.5 从一个下拉列表往另一个下拉列表添加内容 6.6 改变列表项的上下顺序 6.7 给下拉框数据分组 6.8 获取列表框的选择 6.9 类IE下拉框 6.10 下拉框式邮件发送 6.11 获取多选框的选择项 6.12 手动调整的列表框 6.13 ...
比较常用的javascript实例,例如按键捕获,屏蔽右键等实例
6.5 从一个下拉列表往另一个下拉列表添加内容 6.6 改变列表项的上下顺序 6.7 给下拉框数据分组 6.8 获取列表框的选择 6.9 类IE下拉框 6.10 下拉框式邮件发送 6.11 获取多选框的选择项 6.12 手动调整的列表框 6.13 ...
拥有许多实例技巧,相当不错!
javascript 常用 技巧 好用 实例 很多实用的方法和例子来提供方便!
资源名称:网页设计与开发——HTML、CSS、Javascript实例教程内容简介:本书从实用角度出发,详细讲解了HTML、CSS和Javascript的基本语法和设计技巧,通过一个实用的班级网站的规划、设计、实现到发布...
JAVASCRIPT的一些心得技巧,各种有趣的、实用的小例子。
javascript各种实用技巧
1、concat方法 [作用] 将多个数组联合起来,这个方法不会改变现存的数组,它只返回了所结合数组的一份拷贝。 [语法] arrayObj.concat(array1,array2,…) [实例] [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 2...
全书共19章,分别是窗口/框架与导航条设计、表单及表单元素、实用JavaScript函数、日期和时间、文字特效、超级链接特效、操作表格、图形图像与多媒体、页面特效、状态栏特效、报表与打印、网站安全、HTML/CSS样式、...
本课程是一门针对初学者的JavaScript基础入门教程,旨在帮助学习者快速掌握JavaScript编程语言的基本概念和应用技巧。无论你是完全没有编程经验的新手,还是具备其他编程语言知识的学习者,都能从本课程中获得实用的...
全书共19章,分别是窗口/框架与导航条设计、表单及表单元素、实用JavaScript函数、日期和时间、文字特效、超级链接特效、操作表格、图形图像与多媒体、页面特效、状态栏特效、报表与打印、网站安全、HTML/CSS样式、...
此文档为一个实用的Js使用技巧文档,通过实例的操作快速掌握常用的一些开发方式。
本书全部采用知识点与实例相结合的讲解方式,对每个实例的关键知识点都做了细致的注释,让读者通过阅读本书,可以快速掌握用JavaScript制作动态网页的技巧,在短时间内独立建立起有着友好用户体验的网页。...
JavaScript 精彩300例技巧集,chm格式,都是些很实用的JS实例,包括游戏、日期特效、文本特效、按钮、鼠标特效等,还有一部分Java Applet等。
Tcp服务端与客户端的JAVA实例源代码,一个简单的Java TCP服务器端程序,别外还有一个客户端的程序,两者互相配合可以开发出超多的网络程序,这是最基础的部分。 递归遍历矩阵 1个目标文件,简单! 多人聊天室 3...
主要介绍了javascript实现简单的鼠标拖动效果,实例分析了javascript鼠标拖动效果的相关要点与实现技巧,非常具有实用价值,需要的朋友可以参考下
实例128 获取数组中最后一个元素 158 实例129 去除数组中的重复元素 158 实例130 字符串与数组的转换 159 实例131 对数组元素进行随机排序 160 实例132 随机抽取数组中元素 161 实例133 二维数组的输出 162 实例134 ...