简体   繁体   中英

react-native how to assign assign multiple .replace() as a variable?

I am using .replace() method to filter my data.

Like this :

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, '')

The problem is that I need to apply this method in multiple places and I want to assign all the .replace() method as a variable.

edited

I want to assign .replace() as a variable like this

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, '')

So I could use it like this :

this.state.date.toString().slice(13,15).filter

Sounds like you want to extract the logic into a function:

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))

To be less repetitive, you could use an array:

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM