hey got some "simple" text-replace problem ... got an html-page and want to do some easy replacing with a 2 dimensional field
the function "createArray" is out of an answer on a similar question but i cant get this working :
<script type="text/javascript">
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
window.onload = function(){
var tabelle = createArray(14, 2);
tabelle[0][0]="Comment:Header"; tabelle[0][1]="test";
tabelle[1][0]="Comment:Lane"; tabelle[1][1]=" ";
tabelle[2][0]="Comment:VS"; tabelle[2][1]=" ";
tabelle[3][0]="Comment:Early1"; tabelle[3][1]=" ";
tabelle[4][0]="Comment:Early2"; tabelle[4][1]=" ";
tabelle[5][0]="Comment:Early3"; tabelle[5][1]=" ";
tabelle[6][0]="Comment:Mid1"; tabelle[6][1]=" ";
tabelle[7][0]="Comment:Mid2"; tabelle[7][1]=" ";
tabelle[8][0]="Comment:Mid3"; tabelle[8][1]=" ";
tabelle[9][0]="Comment:Late1"; tabelle[9][1]=" ";
tabelle[10][0]="Comment:Late2"; tabelle[10][1]=" ";
tabelle[11][0]="Comment:Late3"; tabelle[11][1]=" ";
tabelle[12][0]="Comment:etc1"; tabelle[12][1]=" ";
tabelle[13][0]="Comment:etc2"; tabelle[13][1]=" ";
for (var i = 0; i < tabelle.length; i++)
document.body.innerHTML =
document.body.innerHTML.replace(tabelle[i][0], tabelle[i][1]);
};
</script>
thx already ;D
More info about your error would help, but I did notice that you had:
for (var i = 0; i <= 14; i++)
instead of the correct:
for (var i = 0; i < 14; i++)
or even better:
for (var i = 0; i < tabelle.length; i++)
Your code works great for me. The problem you having is properbly because you forget to run the srcript after page is loaded. So you might be calling document.body.innerHTML
when document.body
is not there yet.
Remeber to wrap them in
window.onload = function() {
//doing something here
};
Here is a working demo: http://jsfiddle.net/9aP86/1/
Hope it helps.
I would approach this in a different way.
var replacements = {
"Comment:Header": "test",
"Comment:whatever": "test2",
// etc..
};
window.onload = function(event) {
for (var key in replacements) {
if (replacements.hasOwnProperty(key)) {
document.body.innerHTML =
document.body.innerHTML.replace(key, replacements[key]);
};
};
};
I would really avoid the entire hassle. There is a far simpler and more suitable approach to what you are trying to do. And it is also the default way to deal with such things.
typeof replacements["Comment:whatever"] !== 'undefined'
). O(1), no conversions necessary. No searching algorithm required. And HERE is the working Fiddle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.