如何从字符串中提取时间?

时间:2019-06-05 18:23:14

标签: javascript regex

我有一个像这样的字符串:

const string = 'Member has a training (30 Minutes) appointment at 12:00 AM'

是否有可能以某种方式从该字符串中提取时间,以便其返回如下内容:

'12:00 AM'

到目前为止,我已经尝试过

string.replace(/[a-zA-Z]/g, '')

但是它也会从'(30)'的{​​{1}}中离开。还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

{
  "value1": "some value",
  "value2": "some value"
}

正则表达式说明:

ViewChild

答案 1 :(得分:0)

.substring(); -

  

“返回字符串的一部分,从指定的索引开始,然后   之后扩展给定数量的字符。”

const string = 'Member has a training (30 Minutes) appointment at 12:00 AM'
test = string.substring(50,59)

.slice(); -

  

“ slice()方法提取字符串的一部分并将其返回为   新字符串,而无需修改原始字符串。”

test = string.slice(50)

-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice


代码段

const string = 'Member has a training (30 Minutes) appointment at 12:00 AM'

function sliceIt(){
let slice1 = string.substring(50,59);
document.getElementById('slice').innerHTML = slice1;
}

function subStrIt(){
let substr1 = string.slice(50);
document.getElementById('substr').innerHTML = substr1;
}
Extracting time out of "Member has a training (30 Minutes) appointment at 12:00 AM"<hr><input type="button" name="button" id="button" value="Slice" onclick="sliceIt();" \><input type="button" name="button2" id="button2" value="Substr" onclick="subStrIt();" \>
<hr>
Example of slice:
<span id="slice"></span>
<br><br>
Example of substr
<span id="substr"></span>