js 字符串中提取数字与运算符

592 阅读9分钟

需求: 

后端返回字符串 str="2123+{3}*{4}", 提取为前端可用的数组形式 ['2123', '+', '{3}', '{4}']

<script>
	const str = "2123+{3}*{4}"
	const regx = /[+-/\*]/ 
	const numArr = str.split(regx) 
	console.log(numArr) // 提取出数字

	for(let i=1; i<numArr.length; i++) {
		const operatorIndex = str.indexOf(numArr[i]) -1  
		const operator = str.charAt(operatorIndex)
		console.log(operator) // 提取运算符
	}
</script>	

打印结果为: 

合并数组: 

<script>
	let finalArr = []
	const str = "2123+{3}*{4}"
	const regx = /[+-/\*]/ 
	const numArr = str.split(regx) 
	finalArr = JSON.parse(JSON.stringify(numArr)) // 深拷贝
	console.log(numArr) // 提取出数字

	for(let i=1; i<numArr.length; i++) {
		const operatorIndex = str.indexOf(numArr[i]) -1  
		const operator = str.charAt(operatorIndex)
		console.log(operator) // 提取运算符
		finalArr.splice(i, 0 , operator)
	}
	console.log(finalArr)
</script>	

打印结果为: