js - 如何在一行中写入match()的访问返回值

时间:2015-01-16 09:48:44

标签: javascript

这个问题也适用于将数组作为值返回的其他函数。我以为我看到了一个简短的代码:

var result = "12[abc]34".match(/(\[.*?\])/);
alert(result[0]);

那么,有没有办法将2行合并为1并删除声明result的必要性?

3 个答案:

答案 0 :(得分:0)

尝试

("12[abc]34".match(/(\[.*?\])/))[0]

答案 1 :(得分:0)

试试这个

var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0];

如果match返回null,请使用空数组[](因为如果我们在[]中调用null,则会出错;

如果我们需要字符串结果

,我们也可以使用附加条件
var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0] || '';

var result1 = ("12[abc]34".match(/(\[.*?\])/) || [])[0];

console.log(result1);

var result = ("12[abc]34".match(/(\[.*?\])/) || [])[0] || '';

console.log(result)

答案 2 :(得分:0)

使用[0]方法结果直接,只需使用match()

alert("12[abc]34".match(/(\[.*?\])/) ? "12[abc]34".match(/(\[.*?\])/)[0] : "No match found");

给予 - > [ABC]

如果没有找到匹配,那将处理这种情况:

alert("1234".match(/(\[.*?\])/) ? "12[abc]34".match(/(\[.*?\])/)[0] : "No match found");

给予 - >找不到匹配项

This is a working fiddle