转圈圈

string

目录

  1. String.prototype.match
  2. String.prototype.search
  3. String.prototype.replace
  4. 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' ]
posted @ 2019-05-18 10:19  rosendolu  阅读(141)  评论(0编辑  收藏  举报