How split the months from a string?

Viewed 131

I need to split only month names from a string .

Ex :

let str = "januaryfebruaryapriltuesdayfriday";

I want to split like

let arr = ["january","february"," april "]

I am new to JS , I have tried split method ,but i didn't get the result ,is there anyway to do this ?

5 Answers

You could use a regular expression for searching for month names and get an array of it.

var string = "januaryfebruaryapriltuesdayfriday",
    array = string.match(/january|february|march|april|may|june|july|august|september|october|november|december/gi);
    
console.log(array);

You can do something like the following.

To explain, firstly create an array of all the months.

You then want to filter into a new array by only including the months that are in the string.

let months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
];

// change all months to lowercase
months = months.map(m => {
  return m.toLowerCase();
});


let str = "januaryfebruaryapriltuesdayfriday";
let arr = months.filter(m => str.includes(m));

console.log(arr);

You could do something like this

let str = "januaryfebruaryapriltuesdayfriday";
let months=['january','february', 'march', 'april','may','june','july','august','september','october','november','december'];
let arr=[];
months.map((data,index)=>{
if(str.indexOf(data)>=0){
  arr.push(str.substr(str.indexOf(data),data.length))
}}
)
console.log(arr);

You can do it like this:

    let str = "januaryfebruaryapriltuesdayfriday";
    var arr = [];
    if( str.includes("january") ) {
     arr.push("january");
    }
    if( str.includes("february") ) {
     arr.push("february");
    }
    if( str.includes("april") ) {
     arr.push("april");
    }
    console.log(arr);

Continue doing the same for all the months.

How does this work?

This will check if your string contains the names of the months (january, february, march, and so on...) - and if a specific month was found in the string, it will be pushed (appended/added) to the array which is called arr.

Try below code:

var monthsArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
var input = "januaryfeBruaryapriltuesdayfriday";
var inputLowerCase = input.toLowerCase();
var output = [];
monthsArray.forEach(function (month) {
    if (input.includes(month.toLowerCase())) {
        output.push(month);
    }
});
console.log("Output:", output);

// Output: (2) ["January", "April"]

Related