これは私のテキスト文字列です:
0000> hello world <0000
「0000>」から「<0000」までの文字数を数えたい。
これは機能します:
s = "0000> hello my name is james, whats yours? <0000";
s.match(/0000>(.*?)<0000/)[1].length // returns 38;
しかし、もう一度、これもそうです:-)
s.length - 10; // returns 38
さて、このようなものは0000>と<0000の間のすべて(スペースを含む)を数えます:
'0000> hello my name is james, whats yours? <0000'
.split(/0000>|<0000/g)[1].length; //=> 38
または
'0000> hello my name is james, whats yours? <0000'
.replace(/0000>|<0000/g,'').length; //=> 38
これは行います:
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"));
そして、jsfiddleデモ:http ://jsfiddle.net/pSJGk/1/
私は提案します:
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);
ただし、これは最初の一致の後、または2番目の一致の前から空白を削除しません。もちろん、これは、変数を変更するだけで、任意の文字列区切り文字に一致するように変更できます。
参照:
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;
}
使用法:
getLengthBetween("0000> hello my name is james, whats yours? <0000","0000>","<0000");