我正在使用 .replace()
方法来过滤我的数据。
像这样:
this.state.date.toString().slice(13,15)
.replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '')
问题是我需要在多个地方应用此方法,并且我想将所有 .replace()
方法分配为变量。
已编辑
我想将 .replace() 分配为这样的变量
const filter = .replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '')
所以我可以这样使用它:
this.state.date.toString().slice(13,15).filter
最佳答案
听起来您想将逻辑提取到函数中:
const changeToMonthNums = str => str
.replace('Jan', '01')
.replace('Feb', '02')
.replace('Mar', '03')
.replace('Apr', '04')
.replace('May', '05')
.replace('Jun', '06')
.replace('Jul', '07')
.replace('Aug', '08')
.replace('Sep', '09')
.replace('Oct', '10')
.replace('Nov', '11')
.replace('Dec', '12')
.replace(/\s/g, '');
// ...
const thisDateWithMonthNums = changeToMonthNums(this.state.date.toString().slice(13,15))
为了减少重复,您可以使用数组:
const months = ['Jan', 'Feb', 'Mar', ...];
const pattern = new RegExp(months.join('|'), 'g');
const changeToMonthNums = str => str
.replace(
pattern,
match => String(months.indexOf(match) + 1).padStart(2, '0')
)
.replace(/\s/g, '');
const months = ['Jan', 'Feb', 'Mar'];
const pattern = new RegExp(months.join('|'), 'g');
const changeToMonthNums = str => str
.replace(
pattern,
match => String(months.indexOf(match) + 1).padStart(2, '0')
)
.replace(/\s/g, '');
console.log(changeToMonthNums('foo Feb bar'));
关于javascript - react-native 如何分配多个 .replace() 作为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60483198/