简体   繁体   English

正则表达式javascript及匹配结果

[英]Regular expression javascript and match result

I am getting 2 different formats which matches my regular expression.我得到 2 种不同的格式来匹配我的正则表达式。

matches = ['10 am', '5 pm', 'by appointment only']

or或者

['By Appointment :', '10 am', '8 pm' ]

So in first case, the result should be所以在第一种情况下,结果应该是

'10 am to 5 pm by appointment only' “上午 10 点至下午 5 点仅限预约”

For second case, the result should be对于第二种情况,结果应该是

'By Appointment: 10 am to 5 pm' “预约:上午 10 点至下午 5 点”

I tried with below code after joining with 'to'加入“to”后,我尝试使用以下代码

let value = matches.join(' to ');

After joining, this would give text as:加入后,这将给出如下文本:

'10 am to 5 pm to by appointment only' '上午 10 点至下午 5 点至仅限预约'

or或者

'By Appointment: to 10 am to 8 pm' “预约:上午 10 点至晚上 8 点”

if (value.includes('to by appointment only')) {
    value = value.replace('to by appointment only', 'by appointment only');
}
if (value.includes('By Appointment: to')) {
    value = value.replace('By Appointment: to', 'By Appointment:');
}

Basically here I am trying to remove unwanted 'to' text after joining how can I refactor it in better way with the help of regular expression to achieve the same result?基本上在这里,我试图在加入后删除不需要的“to”文本如何在正则表达式的帮助下以更好的方式重构它以获得相同的结果?

You can easily achieve it by iterating the matches array and append the to string if the item ends with am .如果项目以am结尾,您可以通过迭代matches数组和 append to字符串来轻松实现它。 You can check that with the help of String.endsWith()您可以在String.endsWith()的帮助下进行检查

Live Demo :现场演示

 const matches = ['10 am', '5 pm', 'by appointment only']; matches.forEach((item, index) => { if (item.endsWith('am')) { matches[index] = item + ' to ' } }); console.log(matches.join(''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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