计算字符串中2个指定单词之间的字符数

时间:2012-11-10 12:55:53

标签: javascript character

这是我的文字字符串:

0000> hello world <0000

我想计算“0000&gt;”之间的字符数和“&lt; 0000”。

5 个答案:

答案 0 :(得分:2)

这将有效:

s = "0000> hello my name is james, whats yours? <0000";
s.match(/0000>(.*?)<0000/)[1].length // returns 38;

但是又一次,这将是: - )

s.length - 10; // returns 38

答案 1 :(得分:1)

嗯,这样的事情会计算0000&gt;之间的所有内容(包括空格)。和&lt; 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

答案 2 :(得分:1)

这样做:

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/

答案 3 :(得分:0)

我建议:

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);​

JS Fiddle demo

但是,这不会在第一场比赛后或第二场比赛之前修剪空白区域。当然,这可以通过简单地更改变量来匹配任何给定的字符串分隔符。

参考文献:

答案 4 :(得分:0)

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");