[英]Split string by all non-numeric characters
I have a string like this:我有一个这样的字符串:
let s = '10p6s23'
I'd like to split it in such a way that I get the numbers and the letters in an array, so ideally I'd get this:我想以这样一种方式拆分它,即我得到数组中的数字和字母,所以理想情况下我会得到这个:
[10,'p',6,'s',23]
The ultimate goal is to build a add/subtract calculator where p = + and s = -.最终目标是构建一个加法/减法计算器,其中 p = + 和 s = -。 So the string above would resolve to
10 + 6 - 23 = -7
.所以上面的字符串将解析为
10 + 6 - 23 = -7
。
Split string into array on first non-numeric character in javascript 在 javascript 中的第一个非数字字符处将字符串拆分为数组
This worked well, except it only split on the first char, not all chars.这很有效,除了它只在第一个字符上拆分,而不是在所有字符上拆分。
const regexp = /(\d+|[az]+)/g; const str = '10p6s23'; const array = [...str.match(regexp)]; console.log(...array); let replaced = array.map(item => { switch(item) { case 'p': return '+'; case 's': return '-'; default: return item; } }).join(''); console.log(eval(replaced));
One way to do it is by using a Regular Expression一种方法是使用正则表达式
let s = '10p6s23' const numbers = [...s.matchAll(/\d+/g)].map((num) => parseInt(num)); const operators = [...s.matchAll(/\D+/g)]; console.log(numbers); console.log(operators);
And work from here with the rest of the logic并从这里开始使用逻辑的 rest
you can use match function here.你可以在这里使用匹配 function。
'10p6s23'.match(/[a-zA-Z]+|[0-9]+/g)
// /[a-zA-Z]+|[0-9]+/g this is the regular expression for numbers or letters
You could split on:你可以拆分:
(?<=[az])\d+
or(?<=[az])\d+
或(?<=\d)[az]+
(?<=\d)[az]+
Afterwards, you will have the filter on non-empty values.之后,您将对非空值进行筛选。
const regexp = /((?<=[az])\d+|(?<=\d)[az]+)/ig; const str = '10p6s23'; const array = str.split(regexp).filter(x => x.length); console.log(...array);
Here is an iterative replacement solution:这是一个迭代替换解决方案:
const compute = (input) => { let count = input.match(/[ps]/g).length, result = input; while (count --> 0) { result = result.replace( /(\d+)([ps])(\d+)/, (_, left, op, right) => { switch (op) { case 'p': return parseInt(left, 10) + parseInt(right, 10); case 's': return parseInt(left, 10) - parseInt(right, 10); } } ); } return result; }; console.log(compute('10p6s23'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.