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 typeString
– Rakesh_Kumar Commented Mar 2, 2015 at 14:14 - hr[0].replace(/hr/g, '* * *') ? – Millard Commented Mar 2, 2015 at 14:14
4 Answers
Reset to default 3Because 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
版权声明:本文标题:JavaScript: replace string inside array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745495127a2660773.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论