Home > Software engineering >  how to replace everything except "- or " & digit in JavaScript regex
how to replace everything except "- or " & digit in JavaScript regex

Time:10-14

const lat = "-3340Abcs"
const newLat = lat.replace(/\D/g,"") // getting 3340

//expecting -3340

CodePudding user response:

You can use regex /[^- \d]/g

const lat = "-3340Abcs";
const newLat = lat.replace(/[^- \d]/g, "");

console.log(newLat);

CodePudding user response:

I assume your expected result is a number. You can use look behind if you want to also remove and - in the middle of the string:

const lat = "-3340Ab c-s"
const newLat = lat.replace(/(?<=^)[^ -\d]|(?<!^)\D/g,"");

console.log(newLat);

  • Related