-3

This is really puzzling me.

This works fine for me.

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"

However, suppose I put "this is my abc book" into the field, and run this code, there are problems:

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!

It seems to me that .match is returning something which can't be cut by .substr.

I've also tried .split and .substring but not joy.

So in other words, how can I get a substr from a regex match?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
arathra
  • 155
  • 1
  • 11
  • 9
    [*match*](http://ecma-international.org/ecma-262/7.0/index.html#sec-string.prototype.match) returns an Array or *null*, not a string. – RobG Feb 01 '17 at 12:28
  • Please check your console when things does not work properly. There is a possibility of code breaking – Rajesh Feb 01 '17 at 12:30
  • Also use substring instead of substr since substr will confuse you too – mplungjan Feb 01 '17 at 12:30
  • Do you want to get substring from a first match or each match? Because match really returns an array – Andrew Paramoshkin Feb 01 '17 at 12:30
  • @mplungjan I purposely did not change that comment as OP is unaware about the error. Making it a part of question will mislead others – Rajesh Feb 01 '17 at 12:34
  • @Rajesh However when you made is a console.log, it was pretty obvious :) – mplungjan Feb 01 '17 at 13:03
  • Duplicate of http://stackoverflow.com/questions/3486359/regex-to-extract-substring-returning-2-results-for-some-reason – mplungjan Feb 01 '17 at 13:06

1 Answers1

2

.match() will return an array, hence you would need to use index to access the data within result (i.e result[0] instead of result).

Check below snippet.

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!
Pugazh
  • 9,453
  • 5
  • 33
  • 54