Skip to content

Instantly share code, notes, and snippets.

@NV
Created November 18, 2009 13:05
Show Gist options
  • Save NV/237827 to your computer and use it in GitHub Desktop.
Save NV/237827 to your computer and use it in GitHub Desktop.
JS string.between method
/**
* Example:
* 'hello {{username}}'.between('{{','}}') === 'username'
*/
String.prototype.between_regexp = function between(begin, end) {
var regexp = new RegExp(begin + '(.+)' + end);
return this.match(regexp)[1];
}
String.prototype.between_split = function between(head, tail) {
var chunks = this.split(head);
if (typeof chunks[1] === 'undefined') return null;
var middle = chunks[1].split(tail);
if (typeof middle[1] === 'undefined') return null
return middle[0];
}
// Testing Firefox
console.time('between_regexp')
for (var i=0; i<10000; i++) {
'#URL\n\
ID=396\n\
NAME=JS/UIX - Terminal\n\
URL=http://masswerk.at/jsuix/\n\
UNIQUEID=8BDFD6508BD848FABB35F235B2EFD5B6'.between_regexp('NAME=', '\n')
}
console.timeEnd('between_regexp')
/* Results after 3 runs:
192ms
1004ms
190ms
*/
console.time('between_split')
for (var i=0; i<10000; i++) {
'#URL\n\
ID=396\n\
NAME=JS/UIX - Terminal\n\
URL=http://masswerk.at/jsuix/\n\
UNIQUEID=8BDFD6508BD848FABB35F235B2EFD5B6'.between_split('NAME=', '\n')
}
console.timeEnd('between_split')
/* Results after 3 runs:
101ms
98ms
90ms
*/
// TODO: test in all major browsers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment