Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/lib.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,8 @@ declare namespace __String {

function split(this: string, separator?: string | RegExp, limit?: int): string[];

function substr(this: string, start: int, length?: int): string;

function substring(this: string, indexStart: int, indexEnd?: int): string;

function startsWith(this: string, searchString: string, position?: int): boolean;
Expand Down Expand Up @@ -416,6 +418,8 @@ declare class String {

split(this: string, separator?: string | RegExp, limit?: int): string[];

substr(this: string, start: int, length?: int): string;

substring(this: string, indexStart: int, indexEnd?: int): string;

startsWith(this: string, searchString: string, position?: int);
Expand Down
26 changes: 26 additions & 0 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,28 @@ namespace __String {
return strncmp(<string>Ref(this[position]), searchString, lensuffix) == 0;
}

// `length` characters from `start`; a negative start counts from the end
export function substr(this: string, start: int, length: int = this.length): string {
if (start < 0) {
start = start + this.length;
if (start < 0) {
start = 0;
}
} else if (start >= this.length) {
return "";
}

if (length <= 0) {
return "";
}

if (length > this.length - start) {
length = this.length - start;
}

return this.substring(start, start + length);
}

export function substring(this: string, indexStart: int, indexEnd: int = this.length): string {
if (indexStart < 0) {
indexStart = 0;
Expand Down Expand Up @@ -1392,6 +1414,10 @@ export class String {
return this.value.split(separator, limit);
}

public substr(start: int, length?: int): string {
return this.value.substr(start, length);
}

public substring(indexStart: int, indexEnd?: int): string {
return this.value.substring(indexStart, indexEnd);
}
Expand Down
19 changes: 19 additions & 0 deletions tests/string_substr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function main() {
const s = "Mozilla";

assert(s.substr(0, 1) == "M");
assert(s.substr(1, 0) == "");
assert(s.substr(-1, 1) == "a");
assert(s.substr(1, -1) == "");
assert(s.substr(-3) == "lla");
assert(s.substr(1) == "ozilla");
assert(s.substr(-20, 2) == "Mo");
assert(s.substr(20, 2) == "");
assert(s.substr(2, 100) == "zilla");

// through the String wrapper
const w = new String("Mozilla");
assert(w.substr(2, 3) == "zil");

console.log("ALL DONE");
}