我的目标是从字符串中删除后续出现的2个特定字符:点和负号。假设我们有-123-456.78.9.0-12
,之后我应该-123456.789012
。可以通过正则表达式替换吗?
如果我可以添加,我的完整目标是只允许数字,负号和点,只允许负号作为第一个字符或根本不存在。
非常感谢
答案 0 :(得分:3)
您可以在3个replace
来电中执行此操作:
function repl(n) {
return n.replace(/[^\d.-]+/g, '') // remove all non-digits except - and .
.replace(/^([^.]*\.)|\./g, '$1') // remove all dots except first one
.replace(/(?!^)-/g, '') // remove all hyphens except first one
}
console.log(repl('-123-456.78.9.0-12'))
//=> "-123456.789012"
console.log(repl('-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
console.log(repl('-1234'))
//=> "-1234"
console.log(repl('@-123-#456.78.9.0-12-abc-foo'))
//=> "-123456.789012"
下面:
replace
方法正在替换除-
和.
之外的所有非数字字符replace
方法正在替换除第一个之外的每个点。replace
方法正在替换除第一个连字符以外的每个连字符。答案 1 :(得分:0)
如果您想避免使用RegExps,可以执行以下操作:
let str = '-123-456.78.9.0-12';
let output = '';
if (str[0] == '-') output += '-';
let periodIdx = str.indexOf('.');
for (let idx = 0; idx < str.length; idx += 1) {
let char = str.charCodeAt(idx);
if (char > 47 && char < 58) output += str[idx];
if (idx == periodIdx) output += '.';
}
console.log(output);
答案 2 :(得分:0)
如果我可以添加,我的完整目标是只允许数字,负号和点,只允许负号作为第一个字符或根本不存在。
^-?[^.-]*\.?[^.-]*$