Why don't slice () and substr () methods in javascript work with regular expressions?

my code:

var st="man myfile=l/p/nm.mp3 yourfile=/o/mj/nnc.mp3 ou p";
var patt=/myfile.[\W|\w]*.mp3\s/;
var s=patt.exec(st);
var s2=s.slice(3,4);
alert(s2);

      

but slice () gives me nothing and substr () method gives me error:

Object doesn't support this method

Why?

+3


source to share


2 answers


Fabrizio is right. Your variable s

is a RegExp object. To access a substring, you will need:

var s2 = s[0].substr(3,4);

      



jsFiddle here .

+1


source


slice

: The slice () method returns the selected elements in the array as a new array object.

substring

: The substring () method extracts characters from a string, between the two specified indices, and returns a new substring.

var st="man myfile=l/p/nm.mp3 yourfile=/o/mj/nnc.mp3 ou p";
var patt=/myfile.[\W|\w]*.mp3\s/;
var s=patt.exec(st); 

      

s

is now an array containing: ["myfile=l/p/nm.mp3 yourfile=/o/mj/nnc.mp3 "]



var s2=s.slice(3,4);

      

The item 3

does NOT exist, so it returns null

.

Oh, substring

it cannot be used in an array :), so you should do something like this:

var s2=s[0].substring(3,4);

      

0


source







All Articles