字符串常用方法

1、去除前后空格

var str = " hello wrold ";
console.log(str.trim()) // 不改变原数组

2、indexOf(),返回指定字符创第一次出现的位置,找不到返回-1

var str = " hello wrold ";
str.indexOf('h') // 0

3、includes()判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false ES6方法

var str = " hello wrold ";
str.includes('hello') // true

4、replace(),替换指定子串或者与正则表达式匹配的子串,不改变原字符串

var str = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(str.replace('dog', 'monkey')); // 只替换匹配的第一个 
console.log(str.replace(/dog/g, 'monkey')); // 替换所有匹配的

5、substring(),返回一个字符串在开始索引到结束索引之间的一个子集, 或从开始索引直到字符串的末尾的一个子集

var str= "hello world";
console.log(str.substring(0,3)) // hel

6.match(),方法检索返回一个字符串匹配正则表达式的结果,结果是一个数组

var paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
var regex = /[A-Z]/g;
var found = paragraph.match(regex);
console.log(found) // ["T", "I"]

7、split(),将字符串切割成数组

var str= "hello world";
console.log(str.split(" ")); // ["hello","world"];

8、toString(),返回指定对象的字符串形式

9、匹配字符串以什么开头和结尾

// 匹配地址以什么协议开头
var url="http://baidu.com";
url.toLowerCase().startsWith("http://") //true
// 匹配文件名以什么结尾
var fileName = "test.map3";
fileName.toLowerCase().endsWith('.map3'); //true

 

posted @ 2021-07-20 10:13  webHYT  阅读(82)  评论(0)    收藏  举报