假设我有这个字符串“code 123”,我想得到“123”。但有时字符串为空或有其他内容,因此我的代码必须查找错误。所以我可以这样写:
var id = null;
var m = str.match(/code (\d+)/);
if (m && m.length > 1) id = m[1];
if (id) {
...
所以我的问题是,是否有任何方法可以让它与一行或更简单/干净的代码一起工作。像这样的东西:
var id = str.match(/code (\d+)/)[1];
if (id) {
...
但是如果找不到字符串,这会破坏代码。我还可以编写一个函数:
function firstMatch(str, search) {
var m = str.match(search);
if (m && m.length > 1) return m[1];
return null;
}
然后:
var id = firstMatch(str, /code (\d+)/);
if (id) {
...
但我不想在我编写的每个代码中都包含此函数。
最佳答案
var id = (str.match(/code (\d+)/) || [false,false])[1]
如果 (str.match(/code (\d+)/)
为空或 null,则默认为 [false,false]
,使得 [0 ],因此 [1],您要访问的索引,等于 false。然后,
if (id) {
// will not be executed if [1] == false
}
如果 (str.match(/code (\d+)/)
不为 null 或空,则它将优先,并且 if 语句中的代码将被执行,id
将具有来自 (str.match(/code (\d+)/)
关于javascript - 如何在一行中匹配 javascript 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348050/