字符串String

2019-12-18  本文已影响0人  初入前端的小菜鸟

String 对象

String 对象用于处理文本(字符串)。
String 对象创建方法: new String()

语法

var text = new String("string");
或
var text = 'string';

String 对象属性

属性 描述
constructor 对创建该对象的函数的引用
length 字符串的长度
prototype 允许您向对象添加属性和方法

String 对象方法

方法 描述
charAt() 返回在指定位置的字符。
charCodeAt() 返回在指定的位置的字符的 Unicode 编码。
concat() 连接两个或更多字符串,并返回新的字符串。
fromCharCode() 将 Unicode 编码转为字符。
indexOf() 返回某个指定的字符串值在字符串中首次出现的位置。
includes() 查找字符串中是否包含指定的子字符串。
lastIndexOf() 从后向前搜索字符串,并从起始位置(0)开始计算返回字符串最后出现的位置。
match() 查找找到一个或多个正则表达式的匹配。
repeat() 复制字符串指定次数,并将它们连接在一起返回。
replace() 在字符串中查找匹配的子串, 并替换与正则表达式匹配的子串。
search() 查找与正则表达式相匹配的值。
slice() 提取字符串的片断,并在新的字符串中返回被提取的部分。
split() 把字符串分割为字符串数组。
startsWith() 查看字符串是否以指定的子字符串开头。
substr() 从起始索引号提取字符串中指定数目的字符。
substring() 提取字符串中两个指定的索引号之间的字符。
toLowerCase() 把字符串转换为小写。
toUpperCase() 把字符串转换为大写。
trim() 去除字符串两边的空白
toLocaleLowerCase() 根据本地主机的语言环境把字符串转换为小写。
toLocaleUpperCase() 根据本地主机的语言环境把字符串转换为大写。
valueOf() 返回某个字符串对象的原始值。
toString() 返回一个字符串。

简单实用

charAt()

let text = "string";
text.charAt(0)    // 's'

charCodeAt()

let text = "string";
text.charCodeAt(0)   // 115

concat()

let text = 'hello";
let tet = 'world';
let tes = text.concat(tet)    //    "helloworld"
let te = tet.concat(text)      //    "worldhello"

fromCharCode()

String.fromCharCode(115)      //    's'

indexOf

let text = "string";
text.indexOf('s')      // 0

includes()

let text = 'string'
text.includes('ing')    // true;
text.includes('arr')    //  false;

lastIndexOf()

let text = 'asxsa'
text.lastIndexOf('a')        // 4

match()

let str = "The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g);        //  ain,ain,ain

repeat()

let text = 'stirng'
text.repeat(2)  // 'stringstring'
text.repeat(0)  //  ''

replace()

// 常用去除用户输入的空格
let str = '  string ';
str.replace('/^\s+|\s+$/gm,'')    // 'string'

search()

var str="Visit Runoob!"; 
var n=str.search("Runoob");     // 6

slice()

let text = 'hello world!'
text.slice(1,4)      //   'ell'

split()

let text = 'string';
text.split()       // ['s', 't', 'r', 'i', 'n', 'g']

startsWith()

text = 'abc text hello world'
text.startsWith('a')      // true

substr()

let text = 'string'
text.substr(1,2)       //  'tr'

substring()

let text = 'string'
text.substring(1,2)    // 't'

toLowerCase()

let text = "StrinG"
text.toLowerCase()    //  "string"

toUpperCase()

let text = "StrinG"
text.toUpperCase()    //  "STRING"

trim()

let text = ' string ' 
text.trim()    // 'string'

// 去除字符串空白则用的最多为正则
text.replace(/^\s+|\s+$/gm, '')    // 已空格开头或者结尾的用''替换,达到去除空格的作用

toLocaleLowerCase()

valueOf()

let text = "string"
text.valueOf()    // string

toString()

let num = 1;
num.toString()    // '1'
上一篇 下一篇

猜你喜欢

热点阅读