jQuery 在 focusout 上替换

jQuery replace on focusout

我在这个论坛上看了很多遍,但现在我有一个自己的问题。我需要将字符串 01.01.2014 替换为 1. 1. 2014. 我一直未能找到解决方案。这是我离得最近的一次。

$('#date').focusout(function () {
  var strText = $(this).val();
  strReplaceAll = strText.replace( new RegExp( "01", "g" ), "1. " );
  alert(strReplaceAll);
});

但是 return 字符串 1. 1. 21. 4

我已经尝试在 tre RegExp 字符串中使用 .01 但是这个 returns 1. 1. 21.

看来我不能使用“01.”。那么如何做到这一点呢?希望有人能帮我解决这个问题。

迈克尔

您显示的正则表达式似乎不正确。它应该取代 02.02.2014、15.03.2023 等吗?如果是这样,那么你应该使用这个替换:

s.replace(/0(\d+)\./g, '. ')

示例:

'01.01.2014'.replace(/0(\d+)\./g, '. ') // replaces to "1. 1. 2014"
'23.04.2029'.replace(/0(\d+)\./g, '. ') // replaces to "23.4. 2029"
'01.11.2029'.replace(/0(\d+)\./g, '. ') // replaces to "1. 11.2029"

另一个解决方案(没有正则表达式)与前一个解决方案完全一样:

s = '01.01.2014'
s.split('.').map(parseFloat).join('. ') // replaces to "1. 1. 2014"

在 JavaScript 中,您可以使用:

var myregexp = /\b0(\d)\b/g;
result = subject.replace(myregexp, "");