JS数据类型STRING使用实例解析

这篇文章主要介绍了JS数据类型STRING使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

转换为字符串

var num = 10 num.toString(); //"10" 转换为字符串-参数表示几进制的字符串 var stringValue = "hello world"; stringValue.length; //"11" 读取长度

读取字符串指定位置的字符

//下面两行可以读取字符串指定位置的字符--面试题经常遇到 stringValue.charAt(1); //"e" 返回参数位置的字符 stringValue[1]; //"e" 类似于数组的用法 stringValue.charCodeAt(1); //"101" 返回参数位置字符的字符编码 stringValue.concat(" oo"); // "hello world oo" 字符串拼接(不改变原字符串)

字符串的截取

stringValue.slice(start, end); //负数转换为和长度相加 --就是倒数 stringValue.substr(start, len); //第一个参数同上,第二个参数代表长度,所以负值或0,就是截取长度为0的字符串 stringValue.substring(start, end); //较小一个作为起始位置,较大的参数作为结束位置 负值被认为是0

字符串中参数字符的位置

//注意下面两个方法结合,可以判断字符串是某个特定的字符是否有重复 stringValue.indexOf("o"); //4 从前往后找,返回位置 stringValue.lastIndexOf("o"); //7 从后往前找,返回位置 stringValue.indexOf("o",5); //第二个参数代表从该位置开始找 -- 又一个特定字符判重方法

//找出字符串所有的e的位置 var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"; var positions = new Array(); var pos = stringValue.indexOf("e"); while(pos > -1){ positions.push(pos); pos = stringValue.indexOf("e", pos + 1); } alert(positions); //"3,24,32,35,52"

大小写转换

//大小写转换 stringValue.trim();//去前后空格 trimLeft() 和 trimRight() stringValue.toUpperCase(); //"HELLO WORLD" stringValue.toLowerCase(); //"hello world"

模式匹配

match(); //接受一个参数,正则或者RegExp对象 search(); //接受一个参数,正则或者RegExp对象

比较字符串

var stringValue = "yellow"; stringValue.localeCompare("brick"); //1 返回正数 0 负数

其他方法--去空格,替换,分割

var stringValue = "hello world"; stringValue.trim();//去前后空格 trimLeft() 和 trimRight() var text = "cat, bat, sat, fat"; text.replace("at", "ond");//"cond, bat, sat, fat" text.replace(/at/g, "ond");//"cond, bond, sond, fond"--替换所有 text.split(分隔符,指定数组的大小);//按参数分隔符分割 与join相反 String.fromCharCode(104, 101, 108, 108, 111); //"hello" 字符编码拼字符串

ES6新增功能(部分)

字符串的遍历

for (let codePoint of 'foo') { console.log(codePoint) } // "f" // "o" // "o"

字符串的查找

let s = 'Hello world!';//下面第二个参数,表示开始搜索的位置。 s.startsWith('Hello') // true 参数字符串是否在原字符串的头部 s.endsWith('!') // true 参数字符串是否在原字符串的伪部 s.includes('o') // true 参数字符串是否在原字符串内找到

字符串的补全

repeat() //方法返回一个新字符串,表示将原字符串重复n次。 'na'.repeat(2.9) // "nana"小数会被取整,负数或无限会报错 //字符串补全 第一个参数是字符串补全生效的最大长度,第二个参数是用来补全的字符串,不写默认为空格 padStart(); //用于头部补全 padEnd(); //用于尾部补全。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/26c94eea256904e6261666e751b114a5.html