阅读 36

常用字符串的API

1.声明
var myString = new String("Every good boy does fine."); 
var myString = "Every good boy does fine."; 
复制代码
2.截取字符串
//截取第 6 位开始的字符 
var myString = "Every good boy does fine."; 
console.log(myString.substring(6)); //结果: "good boy does fine." 
//截取第 0 位开始至第 10 位为止的字符 
console.log(myString.substring(0,10)); //结果: "Every good" 
//截取从第 11 位到倒数第 6 位为止的字符  
console.log( myString.slice(11,-6)); //结果: "boy does" 
//从第 6 位开始截取长度为 4 的字符 
console.log(myString.substr(6,4)); //结果: "good" 
复制代码
3.转换大小写
var myString = "Hello"; 
var lcString = myString.toLowerCase(); //结果: "hello" 
var ucString = myString.toUpperCase(); //结果: "HELLO" 
复制代码
4.字符串比较
var aString = "Hello!"; 
var bString = new String("Hello!"); 
if( aString == "Hello!" ){ } //结果: true 
if( aString == bString ){ } //结果: true 
if( aString === bString ){ } //结果: false (两个对象不同,尽管它们的值相同) 
复制代码
5.检索字符串
var myString = "hello everybody."; 
// 如果检索不到会返回-1,检索到的话返回在该串中的起始位置 
if( myString.indexOf("every") > -1 ){ } //结果: true 
复制代码
6.查找替换字符串
var myString = "I is your father."; 
var result = myString.replace("is","am"); //结果: "I am your father."
var result = myString.replace(/I |is |\your /g, ''); //替换三个
console.log(myString.replace(/I |is |\your |father/g, '')) //替换四个
复制代码
7.去除收尾空格
var myString = "I is your father.    "; 
console.log(str.trim())
复制代码
8.以子串开头
var myString = "I is your father.    "; 
console.log(str.startsWith("I"))
复制代码
8.查询includes
var myString = "I is your father.    "; 
console.log(str.includes("father"))
复制代码
文章分类
前端
文章标签