如何从字符串中分割月份?

时间:2018-09-19 10:23:26

标签: javascript jquery angularjs node.js

我只需要从字符串中拆分月份名称。

Ex:

let str = "januaryfebruaryapriltuesdayfriday";

我想分裂

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

我是JS的新手,我尝试了split方法,但没有得到结果,是否有这样做的方法?

5 个答案:

答案 0 :(得分:3)

您可以使用正则表达式搜索月份名称并获取其数组。

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

答案 1 :(得分:2)

您可以执行以下操作。

首先,创建一个包含所有月份的数组。

然后,您只想通过包含字符串中的月份来filter进入新数组。

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

答案 2 :(得分:0)

您可以这样做

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

答案 3 :(得分:0)

您可以这样做:

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

在所有月份中继续做同样的事情。

这是如何工作的?

这将检查您的字符串中是否包含月份的名称(一月,二月,三月等),并且-如果在字符串中找到特定的月份,则将其推送(附加/添加)到名为arr的数组。

答案 4 :(得分:0)

尝试以下代码:

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

//输出:(2)[“ January”,“ April”]