.match和.substr的javascript问题无法一起使用

时间:2017-02-01 12:26:44

标签: javascript match substr

这真让我感到困惑。

这对我来说很好。



var result = "this is my abc book";
console.log(result); // displays "this is my abc book"
var res = result.substr(3);
console.log(res); // displays "s is my abc book"




然而,假设我把#34;这是我的abc书"进入该领域,并运行此代码,有问题:



var str = "this is my abc book"; //$(this).val();
console.log(str); // displays "this is my abc book"
var result = str.match(/abc.*/i);
console.log(result); // displays "abc book"
var res = result.substr(3);
console.log(res); // does not display at all!




在我看来,.match正在返回一些无法被.substr剪掉的东西。

我也试过.split和.substring而不是欢乐。

换句话说,如何从正则表达式匹配中获取子函数?

1 个答案:

答案 0 :(得分:2)

.match()将返回一个数组,因此您需要使用索引来访问result内的数据(result[0]而不是result )。

查看下面的代码段。

var str = "this is my abc book"; //$(this).val();
console.log(str); // displays "this is my abc book"
var result = str.match(/abc.*/i);
console.log(result); // displays "abc book"
var res = result[0].substr(3);
console.log(res); // does not display at all!