JavaScript字符串基础知识集锦

来源:互联网 发布:有限元模型是算法吗 编辑:程序博客网 时间:2024/06/14 10:42

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">javascript基本知识集锦(一)</span>

字符串的截取

substring()用于截取两个指定下标之间的字符,不支持负数参数,形式为substring(start,stop);其中start为必需,stop可选。

var test = "This is a good body.";var section = test.substring(4);alert(section);alert(section.length);

slice()可提取字符串的某个部分,并以新的字符串返回被提取的部分,支持负数参数,若参数为负数,则表示从尾部开始计算,截取下标为4~6直接的部分

var test = "This is a good body.";var section = test.slice(4,6);alert(section);alert(section.length);

substr()用于截取下标开始后指定的字符个数,支持负数,其中第二个参数为向后截取的个数

var test = "This is a good body.";var section = test.substr(4,7);alert(section);alert(section.length);
concat()用于连接两个或多个数组,该方法不会改变现有数组,仅仅返回一个连接数组的副本

var a = [1,2,3];var b = [4,5];alert(a.concat(b));alert(a);alert(b);
indexOf()用于返回某个字符串值在字符串中首次出现的位置,如果没用匹配项,则返回-1
<span style="font-family:Tahoma, Helvetica, Arial, 宋体, sans-serif;font-size:12px;"><span style="line-height: 25.2000007629395px; background-color: rgb(247, 252, 255);">lastIndexOf()用于返回某个字符串值在字符串中最后一次出现的位置</span></span>
function IndexDemo(str2){   var str1 = "BABEBIBOBUBABEBIBOBU"   var s = str1.indexOf(str2);   return(s);}IndexDemo("EBI");
charAt()用于返回指定位置的字符
var str="Hello world!"alert(str.charAt(1))
match()用于检查一个字符串是否匹配一个正则表达式

var str="1 plus 2 equal 3"document.write(str.match(/\d+/g))
输出结果为1,2,3









0 0
原创粉丝点击