Extracting some text from a longer text

What’s the equivalent of the javascript code in SC language ?

const str = 'Mozilla';

console.log(str.substring(1, 3));
// expected output: "oz"

The best I found is this:

(
~substr={|str, from, to|
	(from..to).collect{|i| i.postln; str.at(i) }.reduce{|a,b| a++b};
};

~substr.("abcdefgh",0,3);
)

Is there no built-in function for this ?


// Robust version
/*
~substr={|str, from=0, to=nil|
	str.size.debug("size");
	from=from.clip(0,str.size-1);
	to=if(to.isNil){str.size-1}{to.clip(from,str.size-1)};
	(from..to).collect{|i| i.postln; str.at(i) }.reduce{|a,b| a++b};
};
*/
1 Like

Since a String is an array of Chars, you can use .copyRange(start, end):

a  =  "Mozilla";
b =  a.copyRange(1,2); 
-> oz

Best,
Paul

2 Likes

Thanks. That’s all the difficulty with SC. Reflexes, knowledge and habits got from other (mainstream) languages are of little added-value…

Alternatively, because String is an array, you can do this:

a = “Mozilla”;
a[1…2].postln;

Richard

3 Likes