Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

between.as

Name: Between: extract/replace
Author: senocular: www.senocular.com
Date: 1899-12-31T00:00:27.300
Documentation:
String extractBetween and replaceBetween:
Allows replacing or extracting of substrings between two other
strings.

myString.extractBetween(starts, ends [, inclusive]);

Arguments:
- starts: a string to precede the substring to be extracted
- ends: a string to follow the substring to be extracted
- inclusive (optional): if true, includes the starts and ends in the returned strings
Default: false.

Returns:
- an array of all substrings found between starts and ends within the string used on


myString.replaceBetween(starts, ends, replace [, inclusive]);

Arguments:
- starts: a string to precede the substring to be replaced
- ends: a string to follow the substring to be replaced
- inclusive (optional): if true, includes the starts and ends in the replaced strings
Default: false.

Returns:
- a new string with the substrings between starts and ends replaced with replace

Example:
text = "workHard = function(/# args? #/) /# this is where you work hard #/return true; }";
trace(text.replaceBetween("/#", "#/", "", true));
// workHard = function() return true; }
trace(text.replaceBetween("/#", "#/", " comment ", false));
// workHard = function(/# comment #/) /# comment #/return true; }

text = "Sometimes {people} like to {eat} the most {fatty} foods when eat {out}.";
trace(text.extractBetween("{", "}", true));
// {people},{eat},{fatty},{out}
trace(text.extractBetween("{", "}", false));
// people,eat,fatty,out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
String.prototype.extractBetween = function( starts, ends, inclusive){
	var ary = [];
	var str = this;
	var sl = starts.length;
	var el = ends.length;
	var s,e;
	while (str.length) {
		s = str.indexOf(starts);
		if (s == -1) return ary;
		e = str.indexOf(ends, s+sl);
		if (e == -1) return ary;
		if (inclusive) ary.push(str.substring(s, e) + ends);
		else ary.push(str.substring(s+sl, e));
		str = str.substr(e+el);
	}
	return ary;
}
String.prototype.replaceBetween = function( starts, ends, replace, inclusive){
	var r = "";
	var str = this;
	var sl = starts.length;
	var el = ends.length;
	var s,e;
	while (str.length) {
		s = str.indexOf(starts);
		if (s == -1) return r + str;
		e = str.indexOf(ends, s+sl);
		if (e == -1) return r + str;
		if (inclusive) r += str.substr(0, s);
		else r += str.substr(0, s) + starts + replace + ends;
		str = str.substr(e+el);
	}
	return r;
}