0

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
4
  • @CertainPerformance thanks for the reply. You could ignore the .slice() method Commented Mar 2, 2020 at 5:55
  • If you are working on a Date object you can just get month number like this.state.date.getMonth() + 1 Commented Mar 2, 2020 at 5:57
  • What do you mean by I want to assign all the .replace() method as a variable? Do you mean you need a function? Commented Mar 2, 2020 at 6:10
  • @CertainPerformance sorry if i wasn't clear I edited my question :) Commented Mar 2, 2020 at 6:15

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.