我有字符串"11/21/2018 11/27/2018 Thanksgiving Break"
,想从中截取两个日期,并且只检索两个日期(11/21/2018
和(11/27/2018
)以及某种形式的标题数组。
答案 0 :(得分:2)
您可以在匹配这样的组时匹配日期和其他所有内容:
const str = "11/21/2018 11/27/2018 Thanksgiving Break";
const ans = [];
str.replace(/(\d{2}\/\d{2}\/\d{4}) |(.+$)/g, (_, date, text) => {
ans.push(date || text);
});
console.log(ans);
您可以在此处查看正则表达式组的匹配方式:https://regex101.com/r/IXW6Hv/1
答案 1 :(得分:0)
您可以使用split
方法。
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let endOfFirstDate = str.indexOf(" ")
let firstDate = str.substring(0, endOfFirstDate).trim()
let endOfSecondDate = str.indexOf(" ", endOfFirstDate + 1)
let secondDate = str.substring(endOfFirstDate, endOfSecondDate).trim()
let title = str.substring(endOfSecondDate, str.length).trim()
答案 2 :(得分:0)
通常使用正则表达式来完成此操作:
const text = "11/21/2018 11/27/2018 Thanksgiving Break";
console.log(text.match(/([0-9\/]+\s){2}(.+)/)[2])
一种更基本的方法是将字符串拆分为单词,删除前两个,然后再次加入:
const text = "11/21/2018 11/27/2018 Thanksgiving Break";
console.log(text.split(" ").splice(2).join(" "))
答案 3 :(得分:0)
我最简单的方式...
var
Txt = "11/21/2018 11/27/2018 Thanksgiving Break",
pos_1 = Txt.indexOf(' '),
date_1 = Txt.substring(0, pos_1),
pos_2 = Txt.indexOf(' ',++pos_1),
date_2 = Txt.substring(pos_1, pos_2),
msg = Txt.substring(++pos_2);
console.log('__'+ date_1 + '__' +date_2 + '__'+ msg+'__' );
答案 4 :(得分:-1)
if your date is always dd/mm/yyyy style, you can try this one to test it.
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let tmp = str;
tmp = tmp.replace(/[\d]+\/[\d]+\/[\d]+/g," ")
let arr = tmp.split(" ");
for(const item of arr){
if(item){
str = str.replace(item," ");
}
}
for(const item of str.split(" ")){
if(item){
console.log(item);
}
}
if all your data are separate by space, you can try a simple one like below:
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let arr = str.split(" ");
for(const item of arr){
if(/[\d]+\/[\d]+\/[\d]+/.test(item)){
console.log(item);
}
}