This is my text string:
0000> hello world <0000
I want to count the characters between "0000>" and "<0000".
This is my text string:
0000> hello world <0000
I want to count the characters between "0000>" and "<0000".
This will work:
s = "0000> hello my name is james, whats yours? <0000";
s.match(/0000>(.*?)<0000/)[1].length // returns 38;
But then again, so will this :-)
s.length - 10; // returns 38
Well, something like this would count everything (including spaces) between 0000> and <0000:
'0000> hello my name is james, whats yours? <0000'
.split(/0000>|<0000/g)[1].length; //=> 38
Or
'0000> hello my name is james, whats yours? <0000'
.replace(/0000>|<0000/g,'').length; //=> 38
This will do:
function count(string) {
var match = /0000>(.*)<0000/g.exec(string);
if (match.length > 1) {
return match[1].trim().length;
} else {
return null;
}
}
alert (count("0000> hello my name is james, whats yours? <0000"));
And the jsfiddle demo: http://jsfiddle.net/pSJGk/1/
I'd suggest:
var str = " 0000> hello my name is james, whats yours? <0000",
start = "0000>",
end = "<0000",
between = str.substring(str.indexOf(start) + start.length, str.indexOf(end)).length;
console.log(between);
This doesn't, however, trim the white-space from after the first match, or from before the second. This could be altered, of course, to match any given string delimiters by simply changing the variables.
References:
function getLengthBetween(str,startStr,stopStr) {
var startPos = str.indexOf(startStr);
if(startPos == -1) {
return 0;
}
var startOffset = startPos+startStr.length;
var stopPos = str.indexOf(stopStr,startOffset);
if(stopPos == -1) {
stopPos = str.length;
}
return stopPos-startOffset;
}
Usage:
getLengthBetween("0000> hello my name is james, whats yours? <0000","0000>","<0000");