如何删除正则表达式中的第一个数字和逗号?

时间:2019-10-13 01:59:57

标签: javascript regex string replace

如果我有字符串if (this.state.flag === 1) { return <Redirect to='/route' /> } ,该怎么想:["32145","yes","no","0"]?现在,我在下面有正则表达式,但这给了我,"yes","no","0"

,yes,no,

如何删除第一个数字和该数字后的第一个逗号?

3 个答案:

答案 0 :(得分:3)

这是使用JSON.parse()而不使用正则表达式的解决方案。

var str = '["32145","yes","no","0"]';

var result = JSON.parse(str); // Convert string to array.
result.shift(); // Remove first array element.
result = result.toString(); // Convert array to string.

console.log(result);

答案 1 :(得分:2)

也许

\["\d+",|[\]"]

用一个空字符串替换就可以了。

const regex = /\["\d+",|[\]"]/g;
const str = `["32145","yes","no","0"] `;
const subst = ``;

const result = str.replace(regex, subst);

console.log(result);

Demo

RegEx电路

jex.im可视化正则表达式:

enter image description here

答案 2 :(得分:0)

只需解析值并删除第一个元素就是数字

let firstNumRemover = (str) => {
  let removeFurther = true
  return JSON.parse(str).filter(v => {
    if (!isNaN(v) && removeFurther) {
      removeFurther = false
      return false
    }
    return true
  }).toString()
}

console.log(firstNumRemover(`["32145","yes","no","0"]`))
console.log(firstNumRemover(`["Some random text", "32145","yes","no","0"]`))