JS 字符串相关操作
字符串转json – JSON.stringify( a )
json转字符串 – JSON.parse(a)
/** 常用例子:发送websocket请求的时候的json */
const tempSendContent = {}
tempSendContent['id'] = 'uuid'
tempSendContent['reqType'] = 'sub' // 订阅为 sub ,不订阅为 unsub
tempSendContent['api'] = 'api/market/v1/test' // 订阅接口类型
tempSendContent['tempTest1'] = 'test1' // 某某参数 1。。
tempSendContent['tempTest2'] = 'test2' // 某某参数 2。。
tempSendContent['frequency'] = 1000 // 数据更新频率
const sendContent = JSON.stringify(tempSendContent) // object 转 string
const ws = new WebSocket('ws://localhost:9998/test')
ws.send(sendContent)
console.log(tempSendContent) // typeof 检测,结果为 object
// {id: "uuid", reqType: "sub", api: "api/market/v1/test", tempTest1: "test1", tempTest2: "test2", …}
console.log(sendContent) // typeof 检测,结果为 string
// {"id":"uuid","reqType":"sub","api":"api/market/v1/test","tempTest1":"test1","tempTest2":"test2","frequency":1000}
// 输出结果看起来很相似,但 注意 JSON.stringify( object )之后为 string 的 key,是 带双引号 "" 的 ,eg. "id","reqType"
字符串转 数字number
parseFloat
parseFloat("80")
保留几位小数 (四舍五入 & 非四舍五入)
var num =2.446242342;
num = num.toFixed(2); // 输出结果为 2.45
- 先把小数变成 整数
Math.floor(15.7784514000 * 100) / 100 // 输出结果为 15.77
- 当作字符串,使用正则匹配:
Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))
// 输出结果为 15.77,不能用于整数如 10 必须写为10.0000
// 注意:如果是负数,请先转换为正数再计算,最后转回负数
去空格 – replace() + 正则表达式
var str=" 1223 332 ";
console.log(str.length) //控制台输出长度为26
var str_new = str.replace(/\s/ig,'') // / \s / ig , ''
console.log(str_new.length) //控制台输出长度为7
原理:
replace(/\s/ig,’’)
- \s 是匹配任何空白字符,包括空格、制表符、换页符,总之所有空白
- / / 包起来是正则表达式的一种语法格式
- ig 是 “ignore” && “global” 的合并缩写,表示 “忽略大小写,全文查找”,这里的全文对应的当然是 str
- repalce(xxx1,xxx2)是原生的js函数,表示 用xxx2替换掉xxx1 ,
.replace(/(^\s*)|(\s*$)/g,'')
js获取map对象的key、value
var mapObject = {
id1001: 'xiaoming',
id1002: 'xiaohong'
}
// 适合不知道 key 和value的情况,直接遍历
for (var key in mapObject){
var value = mapObject[key]
console.log(value)
}
// 注意,这里的 key 可以是其他命名 ,另外好像必须是 var来定义,用let会爆红,原因不理解~~~~~
js 判断字符串中是否存在 某字符串
var str = '123'
console.log(str.indexOf('3')!= -1 // true
/*
indexOf() 方法可以 返回某个指定的字符串值 在字符串中<u>**首次出现**</u>的位置。
!!!~ 注意,是首次,这个特性可以用在 去重算法中 ~!!!!
如果 检索的字符串值 没有出现 ,则返回 -1
*/
var str = '123'
consolo.log(str.search('3') != -1 // true
/*
search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。
如果没有找到任何匹配的子串,则返回 -1。
*/
stringObject.substring(start,stop)
// start 必需。一个非负的整数,规定要提取的子串的第一个字符在 stringObject 中的位置。
// stop 可选。一个非负的整数,比要提取的子串的最后一个字符在 stringObject 中的位置多 1。 -- 如果省略该参数,那么返回的子串会一直到字符串的结尾。
将时间戳转换为 日期格式
var date = new Date(时间戳); //获取一个时间对象
/**
1. 下面是获取时间日期的方法,需要什么样的格式自己拼接起来就好了
2. 更多好用的方法可以在这查到 -> http://www.w3school.com.cn/jsref/jsref_obj_date.asp
*/
date.getFullYear(); // 获取完整的年份(4位,1970)
date.getMonth(); // 获取月份(0-11,0代表1月,用的时候记得加上1)
date.getDate(); // 获取日(1-31)
date.getDay(); // 获取 周几 ,monday。。
date.getTime(); // 获取时间(从1970.1.1开始的毫秒数)
date.getHours(); // 获取小时数(0-23)
date.getMinutes(); // 获取分钟数(0-59)
date.getSeconds(); // 获取秒数(0-59)
例子:
// 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
var date = new Date(1398250549490);
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
console.log(Y+M+D+h+m+s); //呀麻碟
// 输出结果:2014-04-23 18:55:49
日期相关操作
日期格式 转换为 时间戳
// 也很简单
var strtime = '2014-04-23 18:55:49:123';
var date = new Date(strtime); //传入一个时间格式,如果不传入就是获取现在的时间了,这样做不兼容火狐。
// 可以这样做
var date = new Date(strtime.replace(/-/g, '/'));
// 有三种方式获取,在后面会讲到三种方式的区别
time1 = date.getTime();
time2 = date.valueOf();
time3 = Date.parse(date);
/*
三种获取的区别:
第一、第二种:会精确到毫秒
第三种:只能精确到秒,毫秒将用0来代替
比如上面代码输出的结果(一眼就能看出区别):
1398250549123
1398250549123
1398250549000
*/
- Date()参数形式有7种
new Date("month dd,yyyy hh:mm:ss");
new Date("month dd,yyyy");
new Date("yyyy/MM/dd hh:mm:ss");
new Date("yyyy/MM/dd");
new Date(yyyy,mth,dd,hh,mm,ss);
new Date(yyyy,mth,dd);
new Date(ms);
比如:
new Date("September 16,2016 14:15:05");
new Date("September 16,2016");
new Date("2016/09/16 14:15:05");
new Date("2016/09/16");
new Date(2016,8,16,14,15,5); // 月份从0~11
new Date(2016,8,16);
new Date(1474006780);
本文涵盖了JavaScript中的常见操作,包括字符串转换成JSON、数字转换、保留小数位、去空格的方法,Map对象的处理,判断字符串包含特定子串,时间戳与日期之间的转换等实用技巧。
1048





