Roman Iuvshin
Roman Iuvshin

Reputation: 1912

how to use .replace with match() method javaScript

i need to replace some data obtained from match();

This one return string that contain "Total time: 9 minutes 24 seconds"

data.match(/Total time: [0-9]* minutes [0-9]* seconds/);

but i need only "9 minutes 24 seconds", I try use:

data.match(/Total time: [0-9]* minutes [0-9]* seconds/).replace("Total time:", "");

but there is an error ""

".replace is not a function"

Can some one help me?

Upvotes: 2

Views: 851

Answers (4)

J. K.
J. K.

Reputation: 8368

JavaScript will return an array of matches or null if no match is found. The original code attempts to call the replace method on an instance of an Array instead of the element (a String) within it.

var result = null;
var m = data.match(/.../);
if (m) {
  result = m[0].replace('Total time: ', '');
}

Upvotes: 0

anson
anson

Reputation: 4164

You could get rid of using match doing something like this...

var match = data.replace(/Total time: ([0-9]* minutes [0-9]* seconds)/,"$1");

Upvotes: 1

Riz
Riz

Reputation: 10246

data = 'Total time: 15 minutes 30 seconds';
response = data.match(/Total time: [0-9]* minutes [0-9]* seconds/);
response = response[0];
alert(response.replace("Total time:", ""));

Upvotes: 1

Andy E
Andy E

Reputation: 344715

Use capturing sub expressions in your regex:

var match = data.match(/Total time: ([0-9]* minutes [0-9]* seconds)/);
alert(match[1]);

match() returns an array, which is why you can't call replace on the result — there is no Array#replace method.

Upvotes: 4

Related Questions