1
'Hello there everyone I'm Bob, I want to say something.'

Imagine me having this string, I'm wondering if there is a function which you can give to strings to search for in a string. The first string I is like the start, the second one should be the end. In example: I give the following strings to the function "Hello" and "I'". Then I want the function to return " there everyone " to me.

jQuery will do as well.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Anoniem Anoniem
  • 1,915
  • 6
  • 18
  • 19

3 Answers3

2

You can use .indexOf and .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);

You can of course extract that into a function:

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

Alternatively, you can extend 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 "
Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
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
Sarath
  • 9,030
  • 11
  • 51
  • 84
0

You can use Regular Expression.

str = "Hello there everyone I'm Bob, I want to say something.";
result = str.match(/Hello(.*?)I/);
alert(result[1]);

*? for non-greedy match. http://jsfiddle.net/LV5t3/

iForests
  • 6,757
  • 10
  • 42
  • 75
  • Just wondering; what if my string was 'Hello, they're going to Ibiza, I ' not going.' - How can I get the part after "they'" until "' " ? I can't figure it out. – Anoniem Anoniem Dec 17 '13 at 07:27