'Hello there everyone I'm Bob, I want to say something.'
想象一下,我有这个字符串,我想知道是否有一个函数,你可以给字符串搜索字符串。第一个字符串我就像开始,第二个字符串应该是结束。例如:我给函数“Hello”和“I”提供以下字符串。然后我希望函数将“每个人都”返回给我。
jQuery也会这样做。
答案 0 :(得分:2)
您可以使用.indexOf
和.substring
like so:
var first = str.indexOf("Hello");
var second = str.indexOf("I'm", first + from.length);
var result = str.substring(first + "Hello".length, second);
您当然可以将其提取到函数中:
function between(str, from, to){
var first = str.indexOf(from);
var second = str.indexOf(to, first + from.length);
return str.substring(first + from.length, second);
}
between(yourStr,"Hello","I'm");
或者,您可以延长String.prototype
if that's your thing:
String.prototype.between = function(from, to){
var first = this.indexOf(from);
var second = this.indexOf(to, first + from.length);
return this.substring(first + from.length, second);
}
// now this will work
str.between("Hello","I'm"); // " there everyone "
答案 1 :(得分:2)
var str = "Hello there everyone I'm Bob, I want to say something.";
var first = "Hello";
var second = "I";
var start = str.indexOf(first)+first.length;
var end = str.indexOf(second);
var subStr= str.slice(start , end);
console.log(subStr) // there everyone
答案 2 :(得分:0)
您可以使用正则表达式。
str = "Hello there everyone I'm Bob, I want to say something.";
result = str.match(/Hello(.*?)I/);
alert(result[1]);
*?
用于非贪婪的比赛。 http://jsfiddle.net/LV5t3/