如何在Javascript中从左到右从右到左替换字符串元素? [英] How do I replace elements of string from left-to-right to right-to-left in Javascript?

查看:141
本文介绍了如何在Javascript中从左到右从右到左替换字符串元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的HTML中,我有一个包含5个数字的字符串。单击删除按钮时,数字将按从左到右的顺序替换为短划线。是的,它的作品!但是如何替换从右到左顺序中的数字?

In my HTML I have a string of 5 numbers. When a "delete" button is clicked, numbers are replaced by dashes in left to right order. Yay it works! But how do I replace the numbers in right to left order?

$("#deleteButton").click(function() {
  var str = document.getElementById("dashes").innerHTML;
  var str = str.replace(/[0-9]/, "-");
  document.getElementById("dashes").innerHTML = str;

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dashes">123456789</div>
<button id="deleteButton">delete</button>

推荐答案

你必须确定最右边的数字而不是最左边的数字(正则表达式从左到右搜索) - 默认情况下)。请注意,您可以使用 \d 而不是 [0-9] 来减少语法噪音。一种选择是使用

You'll have to identify the right-most digit rather than the left-most digit (a regular expression searches from left-to-right by default). Note that you can use \d instead of [0-9] for less syntax noise. One option is to use

/\d(?=\D*$)/

也就是说,匹配一个数字,预测任意数量的非数字字符,然后是字符串的结尾。

That is, match a digit, lookahead for any number of non-digit characters, followed by the end of the string.

$("#deleteButton").click(function() {
  var str = document.getElementById("dashes").innerHTML;
  str = str.replace(/\d(?=\D*$)/, "-");
  document.getElementById("dashes").innerHTML = str;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dashes">123456789</div>
<button id="deleteButton">delete</button>

这篇关于如何在Javascript中从左到右从右到左替换字符串元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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