New string functions — part 2

Tamás Kovács
delodi
Published in
2 min readMay 9, 2017

--

My old teacher told me his wisdom: “Programming means, you get the input, manipulate it and display as an output.” The input and the output are both texts, the whole world can be describe as a text.

The JavaScript provides dozens of String manipulating methods, let’s see some of them.

Manipulating strings

Splitting and concatenating strings are very simple. Just set a separator and get an array of the pieces of the string or a concatenated string from our array.

let testString = 'Apple;Pear;Orange';
let testArray = testString.split(';'); // ["Apple", "Pear", "Orange"]
let newString = testArray.join('-'); // "Apple-Pear-Orange"

Slicing, using slice, substr and substring

The average developer would mix up the substr and substring methods, but they have a big difference. The substr's first argument is the starting index, the second argument is the length of the new string. If you don't provide the second argument, the method returns with the rest of the string.

let text = 'abcdefghijklmnopqrstuvz';
console.log( text.substr(2,5)); // "cdefg"
console.log( text.substr(2,0)); // ""
console.log( text.substr(2)); // "cdefghijklmnopqrstuvz"

The slice and substring are more familiar, the first parameter is still the starting index, but the second argument is the index of the last character. The main differences:

If start is bigger stop, then substring will swap those 2 arguments. slice() will NOT swap the arguments.

let text = 'abcdefghijklmnopqrstuvz';
console.log( text.substring(2,5)); // "cde"
console.log( text.substring(5,2)); // "cde"
console.log( text.substring(5)); // "fghijklmnopqrstuvz"console.log( text.slice(2,5)); // "cde"
console.log( text.slice(5,2)); // ""
console.log( text.slice(5)); // "fghijklmnopqrstuvz"

If either argument is negative or is NaN, it will be handled by as zero (o);

let text = 'abcdefghijklmnopqrstuvz';
console.log( text.substring(-5,2)); // "ab"

With slice when stop or start is negative, it will be set as string.length — Math.abs(value).

let text = 'abcdefghijklmnopqrstuvz';
console.log( text.slice(-5,-2)); // "stu"
console.log( text.slice(-2, -5)); // ""
console.log( text.slice(2, -5)); // "cdefghijklmnopqr"

Repeating a string

Sometimes we need to repeat a string, we can do it easily with the repeat method.

'Hello'.repeat(3); // HelloHelloHello

These methods are just some examples from the numerous useful methods of Javascript. Maybe i will return with more :)

--

--