问题与1-4对0-3无关,它与做什么有关String#search
.
String#search
解释你作为正则表达式给出的内容.所以[image]
意味着"任何字符:i
,m
,a
,g
,或者e
"因为[...]
是一个字符类的正则表达式.(稍后,你的String#replace
工作正确,因为如果你给String#replace
一个字符串,它会逐字地使用它.)因此,即使在四次替换之后字符串也有这些字符,你会尝试第五次运行,那就是遇到麻烦的时候.另外,单独地,String#search
返回找到字符串的索引,这将是一个数字(如果未找到,则为-1),这将始终为!== null
.
如果您只是将循环更改为:
while ( text_buffer.indexOf('[image]') !== -1 ) { replaceTag(); }
...你不会超出数组的末尾(只要文本和数组匹配,例如,文本没有[match]
比数组有条目更多的出现).
实例:
var raw_content = {
"text" : "Test image 1 [image] Test image 2 [image] Test image 3 [image] Test image 4 [image]",
"media" :[
{
"src": "http://placehold.it/400x200",
"caption": "This is a caption"
},{
"src": "images/gallery/sh0.png",
"caption": "This is a caption"
},{
"src": "http://placehold.it/400x200",
"caption": "This is a caption"
},{
"src": "images/gallery/sh0.png",
"caption": "This is a caption"
}
]
};
// find img one by one
var image_counter = 0;
var text_buffer = raw_content.text;
var replaceTag = function () {
text_buffer = text_buffer.replace("[image]", raw_content.media[image_counter].src);
/*
console.log(text_buffer);
console.log(image_counter);
console.dir(raw_content.media[image_counter]);
*/
image_counter++;
};
while ( text_buffer.indexOf('[image]') !== -1 ) {
replaceTag();
}
document.body.innerHTML =
'String buiten while loop = ' + text_buffer;