Home > Web Front-end > JS Tutorial > body text

Javascript中的Split使用方法与技巧_基础知识

WBOY
Release: 2016-05-16 19:17:13
Original
1166 people have browsed it

以前很少用Split方法,今天找了些资料。
使用方法:myArray=string.split("|")
说明:"|"为切割特征字符,string为要切割的字符串,myArray为切割结果(存放于数组),使用方法myArray[n],n=myArray.length。
起先我还用asp中的思维在考虑怎么得到myArray的最大下标呢,肯定不是Ubound(myArray),找了半天没找到,最后知道了,其实在Javascript中数组都有一个length属性,myArray.length-1也就是myArray数组的最大下标,很简单吧,想的到真容易,想不到真是难。
来看一个使用split的实例:用javascript获得地址栏参数。

复制代码 代码如下:

<script> <BR><!-- <BR>function Request(strName) <BR>{ <BR>var strHref = "www.nextway.cn/index.htm?a=1&b=1&c=Split实例"; <BR>var intPos = strHref.indexOf("?"); <BR>var strRight = strHref.substr(intPos + 1); <BR>var arrTmp = strRight.split("&"); <BR>for(var i = 0; i < arrTmp.length; i++) <BR>{ <BR>var arrTemp = arrTmp[i].split("="); <BR>if(arrTemp[0].toUpperCase() == strName.toUpperCase()) return arrTemp[1]; <BR>} <BR>return ""; <BR>} <BR>alert(Request("a")); <BR>alert(Request("b")); <BR>alert(Request("c")); <BR>//--> <BR></script> 

获得地址栏参数还有另外一种方法,正则表达式:
复制代码 代码如下:

<script> <BR>String.prototype.getQuery = function(name) <BR>{ <BR>  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); <BR>  var r = this.substr(this.indexOf("\?")+1).match(reg); <BR>  if (r!=null) return unescape(r[2]); return null; <BR>} <BR>var str = "www.nextway.cn/index.htm?a=1&b=1&c=Split实例"; <BR>alert(str.getQuery("a")); <BR>alert(str.getQuery("b")); <BR>alert(str.getQuery("c")); <BR></script> 
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!