这是我的文本字符串:
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/
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");
我建议:
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);
但是,这不会从第一个匹配之后或第二个匹配之前修剪空白。当然,这可以通过简单地更改变量来更改以匹配任何给定的字符串分隔符。
参考: