String interception
1. substring()
xString.substring(start,end)
substring() is the most commonly used string interception method. It can receive two parameters (the parameters cannot be negative values), They are the starting position and the ending position to be intercepted respectively. It will return a new string whose content is all characters from start to end-1. If the end parameter (end) is omitted, it means intercepting from the start position to the end.
let str = 'www.php.cn' console.log(str.substring(0,3)) // www console.log(str.substring(0)) //www.php.cn console.log(str.substring(-2)) //www.php.cn(传负值则视为0)
2. slice()
stringObject.slice(start, end)
slice() method is very similar to the substring() method. The two parameters it passes in also correspond to the starting position. and end position. The difference is that the parameter in slice() can be a negative value. If the parameter is a negative number, the parameter specifies the position starting from the end of the string. That is, -1 refers to the last character of the string.
let str = 'www.php.cn' console.log(str.slice(0, 3)) // www console.log(str.slice(-3, -1)) // co console.log(str.slice(1, -1)) // wwwphp.co console.log(str.slice(2, 1)) // '' (返回空字符串,start须小于end) console.log(str.slice(-3, 0)) // '' (返回空字符串,start须小于end)
3. substr()
stringObject.substr(start,length)
substr() method can extract the specified number of characters starting from the start subscript in the string. The return value is a string containing length characters starting from the start of stringObject (including the character pointed to by start). If length is not specified, the returned string contains characters from start to the end of stringObject. In addition, if start is a negative number, it means counting from the end of the string.
let str = 'www.php.cn' console.log(webStr.substr(1, 3)) // ww. console.log(webStr.substr(0)) //www.php.cn console.log(webStr.substr(-3, 3)) // com console.log(webStr.substr(-1, 5)) // m (目标长度较大的话,以实际截取的长度为准)
4. split()
str.split([separator][, limit])
separator specifies the character (string) used to split the string. separator can be a string or a regular expression. If the separator is omitted, an array of the entire string is returned. If separator is an empty string, str will return an array of each character in the original string.
limit is an integer that limits the number of split fragments returned. The split method still splits each matching separator, but the returned array will only intercept up to limit elements.
let str = 'www.php.cn' str.split('.') // ["www", "php", "cn"] str.split('.', 1) // ["www"] str.split('.').join('') // wwwphpcn
It is said that this function is really easy to use. Many times the character interception requirement depends on a certain character; and the above three functions all need to know its position. Of course we can use indexOf and other methods to obtain it, which is obviously very cumbersome; but using split makes it easier.
Search class methods
1. indexOf() & includes()
stringObject.indexOf(searchValue,fromIndex)
indexOf() is used to retrieve the position where the specified string value first appears in the string. It can receive two parameters, searchValue represents the substring to be searched, and fromIndex represents the starting position of the search. If omitted, the search will be performed from the starting position.
let str = 'www.php.cn' console.log(str.indexOf('.')) // 3 console.log(str.indexOf('.', 1)) // 3 console.log(str.indexOf('.', 5)) // 12 console.log(str.indexOf('.', 12)) // -1
Although indexOf() is used to retrieve the position where the specified string value first appears in the string, many times it is used to determine whether the specified string exists in the string; therefore The code will look like this:
if (str.indexOf('yoursPecifiedStr') !== -1) { // do something }
You must know that in such a scenario, the includes() in the ES6 language is much more elegant; the includes() method is used to determine whether a string is included in another string If it is a string, it returns true, otherwise it returns false.
str.includes(searchString[, position])
searchString The substring to be searched. position is optional. The index position of the current string to start searching for substrings; default is 0. Note that includes() is case-sensitive.
'Blue Whale'.includes('blue'); // returns false '乔峰乔布斯乔帮主'.includes('乔布斯'); // returns true if (str.includes('yoursPecifiedStr')) { // do something(这样写是不是更为人性化?Yeah,这是一个更趋向人性化的时代嘛) }
2. lastIndexOf()
stringObject.lastIndexOf(searchValue,fromIndex)
lastIndexOf() syntax is similar to indexOf(), it returns the last position where a specified substring value appears , the search order is from back to front.
let str = 'www.php.cn' console.log(str.lastIndexOf('.')) // 12 console.log(str.lastIndexOf('.', 1)) // -1 console.log(str.lastIndexOf('.', 5)) // 3 console.log(str.lastIndexOf('.', 12)) // 12 search() stringObject.search(substr) stringObject.search(regexp)
The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. It returns the starting position of the first matching substring, or -1 if there is no match.
let str = 'www.php.cn' console.log(str.search('w')) // 0 console.log(str.search(/j/g)) // 4 console.log(str.search(/\./g)) // 3
match() method
stringObject.match(substr)
stringObject.match(regexp)
match() method can retrieve the specified value within the string, or find one or more regular expressions expression matching.
If the parameter passed in is a substring or a regular expression without global matching, the match() method will perform a match from the beginning. If no result is matched, null will be returned. Otherwise, an array will be returned. The 0th element of the array stores the matching text. In addition, the returned array also contains two object attributes, index and input, which respectively represent the starting character index of the matching text and the stringObject. Reference (i.e. original string).
let str = '#1a2b3c4d5e#'; console.log(str.match('A')); //返回null console.log(str.match('b')); //返回["b", index: 4, input: "#1a2b3c4d5e#"] console.log(str.match(/b/)); //返回["b", index: 4, input: "#1a2b3c4d5e#"]
If the parameter is passed in a regular expression with global matching, then match() will match multiple times from the beginning until the end. If no result is found, null is returned. Otherwise, an array will be returned, which stores all substrings that meet the requirements and has no index and input attributes.
let str = '#1a2b3c4d5e#' console.log(str.match(/h/g)) //返回null console.log(str.match(/\d/g)) //返回["1", "2", "3", "4", "5"]
Other methods
replace() method
stringObject.replace(regexp/substr,replacement)
replace()方法用来进行字符串替换操作,它可以接收两个参数,前者为被替换的子字符串(可以是正则),后者为用来替换的文本。
如果第一个参数传入的是子字符串或是没有进行全局匹配的正则表达式,那么replace()方法将只进行一次替换(即替换最前面的),返回经过一次替换后的结果字符串。
let str = 'www.php.cn' console.log(str.replace('w', 'W')) // www.php.cn console.log(str.replace(/w/, 'W')) // www.php.cn
如果第一个参数传入的全局匹配的正则表达式,那么replace()将会对符合条件的子字符串进行多次替换,最后返回经过多次替换的结果字符串。
let str = 'www.php.cn' console.log(str.replace(/w/g, 'W')) // www.php.cn toLowerCase() & toUpperCase() stringObject.toLowerCase() stringObject.toUpperCase()
toLowerCase()方法可以把字符串中的大写字母转换为小写,toUpperCase()方法可以把字符串中的小写字母转换为大写。
let str = 'wwww.php.cn' console.log(str.toLowerCase()) // www.php.cn console.log(str.toUpperCase()) // WWW.PHP.CN
模板字符串
这个也是 ES6 才引入进来的新语法,来解决传统输出String模板的蹩脚问题;其功能之强大,设计之贴心,着实令人得到极大满足感,好如久旱逢甘霖一般的舒畅。更何况,在当今 MVVM 前端框架大行其道的时代,使用 ES6 语法也是不用自己个儿去操心兼容性问题,对于塑造 Dom Template 更是如虎添翼,令人爱不释手。
对于她的使用,阮一峰在ECMAScript 6 入门有过详细的描述以及示例,在此就不赘述。只需要明白我们可以像这样去操作了,试问爽否?
function ncieFunc() { return "四海无人对夕阳"; } var niceMan = "陈寅恪"; var jadeTalk = `一生负气成今日 \n ${ncieFunc()} , 语出 ${niceMan} 的《忆故居》。 ` console.log(jadeTalk)
运行之,Chrome Console 输出结果如下:
一生负气成今日
四海无人对夕阳 ,
语出 陈寅恪 的《忆故居》。
组合其法
细看 JavaScript 提供的String Api,还是有蛮多的,也有些许废弃的,也有将在未来版本会出来的;这其中不乏很多也挺有用的,譬如: charAt(x)、charCodeAt(x)、concat(v1, v2,…)、fromCharCode(c1, c2,…) 等等,还有 ES6 对字符串的扩展,比如 字符串的遍历器接口,repeat() 等等,这可以参见 ES6-string,这里就不多赘述。
在实际代码生产中,很多时候需要用这些提供的基本方法,来打出一套组合拳,以解决其需求所需。很显然又可以借助 prototype 属性,将自造的各路拳法,其归置于 String 对象,然后天亮啦。这一步就看个人喜好了,这里抛出一二段,以引大玉。
字符串反转
String.prototype.reverse = function () { return this.split('').reverse().join('') }
去除空白行
String.prototype.removeBlankLines = function () { return this.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '') }
String转化为数组
1, 转化为一维数组
场景是根据某子字符串转化,直接就用 split 就好;如果转换规则不统一,那么请自求多福吧。
let Str = '陈寅恪,鲁迅,钱钟书,胡适,王国维,梁启超,吴宓,季羡林' let hallAllOfFameArr = Str.split(',') console.log(hallAllOfFameArr) // ["陈寅恪", "鲁迅", "钱钟书", "胡适", "王国维", "梁启超", "吴宓", "季羡林"]
2, 转化为二维数组
String.prototype.removeBlankLines = function () { return this.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '') } String.prototype.strTo2dArr = function(firstSplit, secondSplit){ var contentStr = this.removeBlankLines(), contentStrArr = contentStr.split(firstSplit), resultArr = contentStrArr.map((element) => { return element.split(secondSplit) }) return resultArr } var str = `
渺渺钟声出远方,依依林影万鸦藏。
一生负气成今日,四海无人对夕阳。
破碎山河迎胜利,残馀岁月送凄凉。
松门松菊何年梦,且认他乡作故乡。
`
console.log(str.strTo2dArr('\n', ','))
运行之,输出结果如下:
[ [ ‘渺渺钟声出远方', ‘依依林影万鸦藏。' ],
[ ‘一生负气成今日', ‘四海无人对夕阳。' ],
[ ‘破碎山河迎胜利', ‘残馀岁月送凄凉。' ],
[ ‘松门松菊何年梦', ‘且认他乡作故乡。' ] ]
以上所述是小编给大家介绍的JavaScript 字符串常用操作小结(非常实用)