0

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?

2
  • hr should be of type String Commented Mar 2, 2015 at 14:14
  • hr[0].replace(/hr/g, '* * *') ? Commented Mar 2, 2015 at 14:14

4 Answers 4

3

Because hr is Array, try this

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

or

hr = hr[0].replace(/hr/g, '* * *');
Sign up to request clarification or add additional context in comments.

1 Comment

replace() returns the result of the operation, it doesn't change the variable on which you invoke it. So try hr = [hr[0].replace(...)]. (Assuming you want to continue having hr being an array)
1

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.