gpt4 book ai didi

javascript - 在javascript中如何从数量字符串中添加或删除 's'

转载 作者:行者123 更新时间:2023-11-30 08:40:42 25 4
gpt4 key购买 nike

我有一个从数据库返回的字符串,例如 7 Months 5 Days

问题是当它是 1 个月 1 天时,它仍然显示为 1 个月 1 天,注意 Months 中的字母 s

而且我不允许使用这样的括号 1 Month(s) 1 Day(s)

请问我如何制定条件,如果少于 2 天,则删除 s

以下内容无效。我该怎么办?

JS

var YYMM = '1 Months 1 Days'; // simulated data.

if (YYMM.indexOf('1') > -1) {
YYMM.replace('s', '');

console.log('YYMM is: ', YYMM);
}

非常感谢

最佳答案

带替换的单个正则表达式可以做到这一点:

var reg = /\b1\b\s(Month|Day)s/g;
alert( '1 Months 1 Days'.replace(reg, '1 $1') );
alert( '11 Months 21 Days'.replace(reg, '1 $1') );
alert( '12 Months 1 Days'.replace(reg, '1 $1') );

关于javascript - 在javascript中如何从数量字符串中添加或删除 's',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26740737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com