Page 1 of 1

[SOLVED] Help fix my infinite loop

Posted: Fri Apr 01, 2005 5:32 am
by Chris Corbyn
Hi,

Me again.... I'm having one my rubbish days where I can't think and nothing's going right :roll:

Code: Select all

xString = 'I have some double &quote;quotes&quote; in me like &quote;this&quote; :-)';
xLength = xString.length;
xIndex = 0; //Position in string
xCount = 0; //Odd or even (opening or closing)
while (xIndex < xLength) {
    if (xString.indexOf('&quote;')) {
        xIndex = xString.indexOf('&quote;')+1; //Position of first quote in string (+1)
        xString = xString.substr(xIndex); //Cut string
        xCount++;
    } else {
        xIndex = xLength;
    }
}
alert(xCount);
I must have this all wrong. Never mind what I need it for (it's a small part of a function). It just crashes the browser. It should skip along the original string counting up each time it hits a double quote.

Thanks :-)

Posted: Fri Apr 01, 2005 6:23 am
by feyd
when indexof doesn't find something, it returns -1.. which will evaluate to true, by default.

Posted: Fri Apr 01, 2005 6:30 am
by Chris Corbyn
Grrr... I can fix that then :lol:

I've been sat here scribbling on paper for ages testing it in my own head and think god dammit - it works! LOL :-)

Thanks for spotting that.

EDIT | Great:

Code: Select all

xString = 'I have some double &quote;quotes&quote; in me like &quote;this&quote; :-)';
xLength = xString.length;
xIndex = 0; //Position in string
xCount = 0; //Odd or even (opening or closing)
while (xIndex < xLength) {
    if (xString.indexOf('&quote;') != -1) {
        xIndex = xString.indexOf('&quote;')+1; //Position of first quote in string (+1)
        xString = xString.substr(xIndex); //Cut string
        xCount++;
    } else {
        xIndex = xLength;
    }
}
alert(xCount);