admin管理员组

文章数量:1427340

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?

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?

Share Improve this question asked Mar 2, 2015 at 14:12 wycwyc 55.4k83 gold badges256 silver badges441 bronze badges 2
  • hr should be of type String – Rakesh_Kumar Commented Mar 2, 2015 at 14:14
  • hr[0].replace(/hr/g, '* * *') ? – Millard Commented Mar 2, 2015 at 14:14
Add a ment  | 

4 Answers 4

Reset to default 3

Because hr is Array, try this

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

or

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

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

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, '* * *');
}

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.

本文标签: JavaScript replace string inside arrayStack Overflow