Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js字符串|数组的操作方法 #12

Open
aermin opened this issue Feb 13, 2018 · 0 comments
Open

js字符串|数组的操作方法 #12

aermin opened this issue Feb 13, 2018 · 0 comments
Labels

Comments

@aermin
Copy link
Owner

aermin commented Feb 13, 2018

字符串

split()

mdn

用法:string.split(separator,limit) ,与join相反

例子:

var a="0,1,2,3,4,5,6";
a.split(""); //["0", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6"]

var a="0,1,2,3,4,5,6";
a.split("",3); // ["0", ",", "1"]

var a="0,1,2,3,4,5,6";
a.split(",",3);  // ["0", "1", "2"]

substr()

mdn

方法返回一个字符串中从指定位置开始到指定字符数的字符。

var str = "abcdefghij";

console.log(str.substr(1,2));   // (1,2): bc
console.log(str.substr(-3,2));  // (-3,2): hi
console.log(str.substr(-1,1));  //  返回最后字符串的一个字符  j

replace()

mdn

返回一个由替换值替换一些或所有匹配的模式后的新字符串。模式可以是一个字符串或者一个正则表达式, 替换值可以是一个字符串或者一个每次匹配都要调用的函数。

用法:str.replace(regexp|substr, newSubStr|function)

var str = 'Twas the night before Xmas...';
newstr = str.replace('Twas', 'Christmas'); //"Christmas the night before Xmas..."
//或者
var str = 'Twas the night before Xmas...';
newstr = str.replace(/xmas/i, 'Christmas'); // Twas the night before Christmas...

先更新到这,更多操作string的api看mdn的string实例

数组

splice和slice的异同点
同:
1.都是返回切割下来的数组
2.初始位置都是从0开始算
异:
1.splice 改变原数组 而slice不会
2.splice三个参数分别是初始位置,删除数量,替换的内容
而slice两个参数分别是初始位置和终点位置

var months = ['Jan', 'March', 'April', 'June'];
console.log(months.splice(1, 0, 'Feb')); // []
console.log(months); //  ["Jan", "Feb", "March", "April", "June"]
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals); // ["ant", "bison", "camel", "duck", "elephant"]
@aermin aermin changed the title 简单的方法掌握JS中slice,splice和split的使用方法 简单的方法掌握JS中slice,splice和split的使用方法(2017.10.15) Feb 13, 2018
@aermin aermin changed the title 简单的方法掌握JS中slice,splice和split的使用方法(2017.10.15) js字符串的操作方法 Mar 8, 2018
@aermin aermin changed the title js字符串的操作方法 js字符串|数组的操作方法 Jul 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant