javascript中字符串操作

2019-01-29  本文已影响0人  这里王工头

欢迎访问我的博客https://qqqww.com/,祝所有码农同胞们早日走上人生巅峰,迎娶白富美~~

String :

  1. javascript检测字符串
  2. javascript去除字符串空格
  3. URL中查询字符串中的参数
  4. javascript字符串的常用函数

检测string类型

方法一:typeof

function isString (str) {
    return typeof (str) === 'string' ? true : false
}

方法二:constructor

function isString (str) {
    return str.constructor === String ? true : false
}

去除字符串空格

方法一:replace()

使用replace匹配正则,\s匹配任何空白字符,包括空格、制表符、换页符等等

var str = '  aaaa bcs  dsda   '
str = str.replace(/\s*/g, '') // 去除所有空格
str = str.replace(/^\s|\s$/g, '') // 去除两头空格
str = str.replace(/^\s/g, '') // 去除左空格
str = str.replace(/\s$/g, '') // 去除右空格

方法二:trim()

局限:无法去除中间的空格

var str = '  aaaa bcs  dsda   '
str = str.trim() // aaaa bcs  dsda

获取URL中查询字符串参数

split

测试地址为:http://www.runoob.com/jquery/misc-trim.html?channelid=12333&name=xiaoming&age=23

// window.location.href = "http://www.runoob.com/jquery/misc-trim.html?channelid=12333&name=xiaoming&age=23"
var a = window.location.href
var b = a.split('?') // b[1] = "channelid=12333&name=xiaoming&age=23"
var c = b[1].split('&')
for (var i = 0; i < c.length; i++) { console.log(c[i].split('=')) }
// 此时可遍历出 ? 后面参数的每一项

其他常用字符串函数

看下面控制台输出结果:

String StringFunction
上一篇下一篇

猜你喜欢

热点阅读