假设我有一个字符串“代码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) {
...但我不想在我编写的每一段代码中都包含这个函数。
发布于 2016-10-31 18:17:16
var id = (str.match(/code (\d+)/) || [false,false])[1]
如果(str.match(/code (\d+)/)为空或空,它将默认为[false,false],从而生成您要访问的索引,等于false。然后,
if (id) {
// will not be executed if [1] == false
}如果(str.match(/code (\d+)/)为而非空或空,则优先执行If语句中的代码,id将具有(str.match(/code (\d+)/)中的非空、非空值。
发布于 2016-10-31 18:23:00
您可以将匹配结果分配给局部变量,如果它不是null /未定义,则访问它的第一个索引,否则使用空字符串或空字符串数组--只需使用最适合您的场景。
var id = (m=str.match(/code (\d+)/)) ? m[1] : "";JS演示:
var res = (m="Some code 55".match(/code (\d+)/)) ? m[1] : "";
console.log(res);
res = (m="No code".match(/code (\d+)/)) ? m[1] : "";
console.log(res);
发布于 2016-10-31 18:19:08
var s = "some string";
var result = (s.indexOf("123") > -1) ? true : false;https://stackoverflow.com/questions/40348050
复制相似问题