码迷,mamicode.com
首页 > 其他好文 > 详细

字符串常用的方法

时间:2016-12-29 16:40:24      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:检查   字符   hand   组合   空格   正则表达   bst   声明   ace   

 字符串的常用属性及方法:

检查字符串的长度(length):

(function handleStr(str){

console.log(str.length);

})(‘abc‘);

合并两个字符串(concat):

将两个或多个字符的文本组合起来,返回一个新的字符串。

//let声明和var声明:var 声明全局变量;let声明块级变量

//(function handle(){

//  let a=10

//  if(true){

//   let a=20;

//  console.log(a);//20

//}

// console.log(a);//10

//})() 

let a=‘hello‘;

let b=‘world‘;

console.log(a.concat(b))//helloworld

indexOf /lastIndexOf

返回字符串中一个子串第一处出现的索引(从左到右搜索)。如果没有匹配项,返回 -1 。

返回字符串中一个子串最后一处出现的索引(从左到右搜索)。如果没有匹配项,返回 -1 。

let a=‘hello‘;

console.log(a.indexOf(‘l‘));//2

console.log(a.lastIndexOf(‘l‘));//3

charAt
返回指定位置的字符(按照下标切)。 

let a=‘hello‘;

console.log(a.charAt(1));//e

match
检查一个字符串匹配一个正则表达式内容,如果么有匹配返回 null。

let a=‘hello‘;

console.log(a.match(1));//null

substring
返回字符串的一个子串,传入参数是起始位置和结束位置(下标)(当参数为负数时,会自动从0开始)。

let a=‘hello‘;

 console.log(a.substring(1,2));//e

 substr

返回字符串的一个子串,传入参数是起始位置和长度

let a=‘hello‘;

console.log(a.substr(1,2));//el 

replace

用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。

let a=‘hello‘;

console.log(a.replace(‘he‘,‘she‘));//shello

 search

执行一个正则表达式匹配查找。如果查找成功,返回字符串中匹配的索引值。否则返回 -1 。

let a=‘hello‘;

console.log(a.substr(‘h‘));//0

slice

提取字符串的一部分,并返回一个新字符串(当参数为负数时,系统会自动加字符串的长度作为起始位置)。

let a=‘hello‘;

console.log(a.slice(1,2));//e

 split

通过将字符串划分成子串,将一个字符串做成一个字符串数组。

let a=‘hello‘;

console.log(a.split(‘‘));//[‘h‘,‘e‘,‘l‘,‘l‘,‘o‘]

 toLowerCase

将整个字符串转成小写字母。

let a=‘HELLO‘;

 console.log(a.toLowerCase());//hello

 toUpperCase

将整个字符串转成大写字母。

let a=‘hello‘;

console.log(a.toUpperCase());//HEELO

 trim

去除整个字符串前后的空格。

let a=‘  hello ‘;

console.log(a.trim());//hello

 

字符串常用的方法

标签:检查   字符   hand   组合   空格   正则表达   bst   声明   ace   

原文地址:http://www.cnblogs.com/QxkWeb/p/6233222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!