javascript中字符串操作 - Go语言中文社区

javascript中字符串操作


javascript中字符串操作

欢迎访问我的博客,祝码农同胞们早日走上人生巅峰,迎娶白富美~~~

String :

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

检测string类型

方法一:typeof

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

方法二:constructor

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

去除字符串空格

方法一:replace()

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

1
2
3
4
5
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()

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

1
2
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

1
2
3
4
5
6
// 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

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_43307658/article/details/88845093
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢