wyc
wyc

Reputation: 55263

JavaScript: replace string inside array

Maybe I'm making a very stupid mistake but here it goes. I want to take [ 'hr' ] and turn it into [ '* * *' ] So I did this:

var hr = jsonml[i]

console.log(hr)
// outputs: [ 'hr' ]
hr.replace(/hr/g, '* * *')

But I get this error:

TypeError: Object hr has no method 'replace'

What am I doing wrong?

Upvotes: 0

Views: 6463

Answers (4)

curlybracket
curlybracket

Reputation: 433

hr is an array containing one string element. I would do this way:

if (hr.length > 0)
    hr[0] = hr[0].replace(/hr/g, '* * *');

EDIT: or maybe

for (var i = 0; i < hr.length; i++)
    hr[i] = hr[i].replace(/hr/g, '* * *');

if hr may contain more than one element

Upvotes: 1

Peter Herdenborg
Peter Herdenborg

Reputation: 5962

Just for the sake of providing an answer that actually does what OP asks for (no more, no less):

hr = [hr[0].replace('hr', '* * *')];

No need to use a regular expression when replacing in this case.

Upvotes: 0

Pippi
Pippi

Reputation: 323

You can see the typeof of object :

alert(typeof hr);

you will see thath this object is an array!

use this :

for (i = 0; i < hr.length; i++) {
  var result = hr[i].replace(/hr/g, '* * *');
}

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

Because hr is Array, try this

hr[0] = hr[0].replace(/hr/g, '* * *');

or

hr = hr[0].replace(/hr/g, '* * *');

Upvotes: 3

Related Questions