string
目录
- String.prototype.match
- String.prototype.search
- String.prototype.replace
- String.prototype.split
String.prototype.match
返回匹配成员组成的数组,没有则返回null
var s = '_x_x';
var r1 = /x/;
var r2 = /y/;
s.match(r1), // [ 'x', index: 1, input: '_x_x', groups: undefined ]
s.match(/x/g), // [ 'x', 'x' ]
String.prototype.search
返回第一个匹配在字符串中的位置,没有则返回 -1
'_x_x'.search(/x/) // 1
String.prototype.replace
参数:(表达式,替换值 | 回调函数 ) 返回替换之后的字符串
'aaa'.replace('a', 'b') // "baa"
'aaa'.replace(/a/, 'b') // "baa"
'aaa'.replace(/a/g, 'b') // "bbb"
应用
消除字符串中 首尾 的空格
var str = ' div.container > item '
str.replace(/^\s+|\s+$/g,'') // "div.container > item"
// str.trim() 也可以实现
反转字符串
'hello world'.replace(/(\w+)\s(\w+)/, '$2 $1')
// "world hello"
'3 and 5'.replace(/[0-9]+/g, function (match) {
return 2 * match;
})
// "6 and 10"
String.prototype.split
'a, b,c, d'.split(/,\s*/) // ["a", "b", "c", "d"]
// 指定返回数组的最大成员
'a, b,c, d'.split(/, */, 2)
[ 'a', 'b' ]