简体   繁体   English

如何替换JavaScript正则表达式中除“-或+”和数字之外的所有内容

[英]how to replace everything except "- or +" & digit in JavaScript regex

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

//expecting -3340

You can use regex /[^-+\\d]/g您可以使用正则表达式/[^-+\\d]/g

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

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+cs" const newLat = lat.replace(/(?<=^)[^+-\\d]|(?<!^)\\D/g,""); console.log(newLat);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM