《JavaScript Api》系列之字符串方法操作集合(match、模版字符串、隐式包装)

382 阅读5分钟

前言

字符串是一个或多个字符的序列,可以由字母,数字或符号组成。

JavaScript 中的字符串是基本数据类型,在业务开发中,单独操作字符串的场景相对较少,但却是不可忽略的基础,本文整理了比较常用的字符串方法,希望本文对你有所帮助。

常用的String原型方法

字符串包含

includes

检查字符串是否包含指定的字符

const str = '你好,欢迎来到海洋里的魔鬼鱼';
console.log(str.includes('海洋里')) // > true

startsWith

检查字符串是否以指定的字符开头

const str = '你好,欢迎来到海洋里的魔鬼鱼';
console.log(str.startsWith('海洋里')) // > false
console.log(str.startsWith('你好')) // > true

endsWith

检查字符串是否以指定的字符开头

const str = '你好,欢迎来到海洋里的魔鬼鱼';
console.log(str.endsWith('海洋里')) // > false
console.log(str.endsWith('魔鬼鱼')) // > true

获取字符串索引

charAt

返回指定位置的字符

return 'cat'.charAt(1); // returns "a"

indexOf

返回字符串中第一处出现的索引,如果没有匹配值,返回-1

const paragraph = '你好,在干嘛';
const searchTerm = '嘛';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(indexOfFirst) // 5

lastIndexOf

返回字符串中最后一处出现的索引,如果没有匹配值,返回-1

const paragraph = '你好,你在干嘛?';
const searchTerm = '你';
const indexOfFirst = paragraph.lastIndexOf(searchTerm);
console.log(indexOfFirst) //3

search

进行正则匹配查找。如果查找成功,返回字符串中匹配的索引值,否则返回-1

const str = '你好,编号为:10086';
console.log(str.search('[1-9]\d*')) // > 7 

match

字符串匹配。若有相匹配的字符,则返回所要匹配的字符串,否则返回 null

const str = '你好,编号为:10086';
console.log(str.match('[1-9]\d*')) // > Array['1']

字符串截取

substring

返回字符串两个索引之间(或到字符串末尾)的子串

const paragraph = '你好,朋友欢迎来到海洋里的魔鬼鱼';
console.log(paragraph.substring(6,10)); //> "迎来到海"

slice

提取字符串的一部分,并返回一个新字符串。

const paragraph = '你好,朋友欢迎来到海洋里的魔鬼鱼';
console.log(paragraph.slice(5)); //> "欢迎来到海洋里的魔鬼鱼"

substr

返回从string的start位置,长度为length的字符串

const paragraph = '你好,朋友欢迎来到海洋里的魔鬼鱼';
console.log(paragraph.slice(5)); //> "欢迎来到海洋里的魔鬼鱼"
console.log(paragraph.slice(-4)); //> "的魔鬼鱼"

字符串替换

replace

用字符串中的另一个值替换指定的值,区分大小写

const str = '你好,朋友欢迎来到海洋里的魔鬼鱼';
console.log(str.replace(',朋友','伙伴'));  // > "你好伙伴欢迎来到海洋里的魔鬼鱼"

字符串重复

repeat

返回一个新字符串,表示将原字符串重复n次

const str = '你好,朋友欢迎来到海洋里的魔鬼鱼';
console.log(str.repeat(2));  // > "你好,朋友欢迎来到海洋里的魔鬼鱼你好,朋友欢迎来到海洋里的魔鬼鱼"

字符串补全

padStart

用于将字符串头部补全长度

const str = '你好,朋友';
console.log(str.padStart(10,'haha'));  //> "hahah你好,朋友"

padEnd

用于将字符串尾部补全长度

const str = '你好,朋友';
console.log(str.padEnd(10,'haha'));  //> "你好,朋友hahah"

字符串转换

toLocaleLowerCase

将字符串转换为小写字母,改变字符串本身

'ALPHABET'.toLocaleLowerCase(); // 'alphabet'

toLocaleUpperCase

将字符串转换为大写字母,改变字符串本身

'alphabet'.toLocaleUpperCase(); // 'ALPHABET'

toLowerCase

将字符串转换为小写字母,返回一个新的字符串

console.log('ALPHABET'.toLowerCase()); // 'alphabet'

toUpperCase

将字符串转换为大写字母,返回一个新的字符串

console.log('alphabet'.toUpperCase()); // 'ALPHABET'

字符串分割

split

将字符串拆分为数组

const str = 'hello my friends';
console.log(str.split(' '));  // > Array ["hello", "my", "friends"]

其他

Sting 还有需要方法,由于使用频率非常低,在这里就不叙述了,比如合并字符串,还有可以直接返回带有样式的字符串,功能实在鸡肋。

其他常用操作

模版字符串

es6 的模板字符串让我们处理字符串更加容易,尤其是我们在渲染前端界面展示数据时,大大减少了代码量,加强了易读性。

表达式

未使用模版字符串前

var a = 20;
var b = 10;
var c = "JavaScript";
var str = "My age is " + (a + b) + " and I love " + c;
console.log(str);

使用模版字符串后

const a = 20;
const b = 10;
const c = "JavaScript";
const str = `My age is ${a+b} and I love ${c}`;
console.log(str);
//output “My age is 30 and I love JavaScript"

字符串换行

在ES6之前我们只能使用"\n“在字符串中进行换行。

console.log("1\n2\n3");

在ES6中,我们可以直接输入回车进行换行。

console.log(`1
2
3`);

函数

var fn1 = function(){
    console.log('hello vuex');
}
var fn2 = function(){
    return 'hello vue-router'
}
`xxx ${fn1}`   //xxx function fn(){....}
`xxx ${fn1()}` //xxx underfind
`xxx ${fn2()}` //xxx hello vue-router

检测string类型

typeof

function isString (str) {
    return typeof (str) === 'string' ? true : false
}

constructor

function isString (str) {
    return str.constructor === String ? true : false
}

去除字符串空格

replace

使用 replace 匹配正则,\s匹配任何空白字符,包括空格、制表符、换页符等等

var str = '  aaaa bcs  dsda   '
str = str.replace(/\s*/g, '') // 去除所有空格
str = str.replace(/^\s|\s$/g, '') // 去除两头空格
str = str.replace(/^\s/g, '') // 去除左空格
str = str.replace(/\s$/g, '') // 去除右空格

trim

局限:无法去除中间的空格

var str = '  aaaa bcs  dsda   '
str = str.trim() // aaaa bcs  dsda

隐式包装

String 作为基本类型数据,它是一个值,不是一个对象,一个值怎么会有属性和方法呢?

JavaScript 为了方便我们操作对应的基本类型数据,会在我们调用属性或是方法前,对基本类型数据作一个包装,简单理解就是用了隐秘的方法,将基本类型包装成一个对象,在我们使用完这个对象的方法后,在将对象销毁。

这个过程叫作 基本包装类型 也叫 隐式包装

var str = "我是string基本类型的值";
var new_str = new String("我是string基本类型的值");  // 包装处理
var my_str = new_str.substring(5,8);
new_str = null;   // 方法调用之后销毁实例

结尾

如果这篇文章帮助到了你,欢迎点赞和关注,搜索《海洋里的魔鬼鱼》加入我们的技术群一起学习讨论,共同探索前端的边界。