在Javascript中删除字符串的前导零 [英] Remove leading zeros of a string in Javascript

查看:60
本文介绍了在Javascript中删除字符串的前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我需要从字符串
中删除任何前导零,如 02-03 02& 03 02 03 。我有这个正则表达式( s.replace(/ ^ 0 + /,''); )来删除前导零,但我需要一些适用于上述情况的东西。

I have a scenario where I need to remove any leading zeros from a string like 02-03, 02&03, 02,03. I have this regex( s.replace(/^0+/, ''); ) to remove leading zeros but I need something which works for the above cases.

var s = "01";

s = s.replace(/^0+/, '');

alert(s);

推荐答案

最简单的解决方案可能是使用这样的单词边界( \b ):

The simplest solution would probably be to use a word boundary (\b) like this:

s.replace(/\b0+/g, '')

这将删除任何前面没有拉丁字母,十进制数字,下划线的零。全局( g )标志用于替换多个匹配(没有它只会替换找到的第一个匹配)。

This will remove any zeros that are not preceded by Latin letters, decimal digits, underscores. The global (g) flag is used to replace multiple matches (without that it would only replace the first match found).

$("button").click(function() {
  var s = $("input").val();
  
  s = s.replace(/\b0+/g, '');
  
  $("#out").text(s);
});

body { font-family: monospace; }
div { padding: .5em 0; }
#out { font-weight: bold; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input value="02-03, 02&03, 02,03"><button>Go</button></div>
<div>Output: <span id="out"></span></div>

这篇关于在Javascript中删除字符串的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆