DEV Community

Cover image for The many ways to select the n-th character from a string.
Christian Heilmann
Christian Heilmann

Posted on • Updated on

The many ways to select the n-th character from a string.

A question I came across the other day during a JavaScript application test was this:

How would you select the n-th character from the word "Example"?

The fun thing here is that there are lots of different ways to do that. The one I always forget about is that you can access the index of a string directly. This works in JavaScript and PHP!

'example'.substr(1,1) // (from, how many characters)
'example'.substring(1,2) // (from, to)
'example'.at(1)
'example'.split('')[1] // split turns it into an array
[... 'example'][1] // convert to array via spread
'example'[1] // 🤯 
Enter fullscreen mode Exit fullscreen mode

Now, when checking that a string is a certain length, you normally use the length property, but you could also simply check if the index exists, to make it shorter.

let str = 'example';
let amount = 4;
if (str.length > amount) {
    console.log('string is long enough');
}
if (str[amount]) {
    console.log('string is long enough');
}
Enter fullscreen mode Exit fullscreen mode

The question is if this performs better or not. Also, the length bit might make it more readable.

Other problems are that zero-indexing can be confusing (hence the amount+1) and that when you use the index you don't get a boolean returned but instead the character or undefined. So if you wanted to write this as a function you need to write something akin to:

const isXlong = (str, y) => str[y + 1] ? true : false;
Enter fullscreen mode Exit fullscreen mode

Which makes it less readable again.

Top comments (11)

Collapse
 
codepo8 profile image
Christian Heilmann

Yes, the +1 isn't needed.

Collapse
 
bbkr profile image
Paweł bbkr Pabian

I'm pretty sure you forgot about regexp method :)

Fun fact: in this area Raku language adds another animal to cabinet of curiosities, allowing to specify n-th match as modifier:

$ raku -e 'say "abcde" ~~ m:3rd/(.)/'
「c」

$ raku -e 'say "abcde" ~~ m:nth(5)/(.)/'
「e」
Enter fullscreen mode Exit fullscreen mode

Which is actually pretty useful in everyday use.

Collapse
 
codepo8 profile image
Christian Heilmann

Now, that would be really slow

Collapse
 
bbkr profile image
Paweł bbkr Pabian

Of course. Spinning up regular expression engine to do something that trivial is waste of CPU. Chopping string into characters is also not optimal because it copies unused characters in memory.

My post was simply adding another funny way to pile of TIMTOWTDI.

Collapse
 
efpage profile image
Eckehard

Javascript provides an awful lot of redundant ways to solve the same task, and I´m not sure if this really is an advantage. Finally, a programming language is just a tool to tell the computer, what to do. Using different ways to do the same thing is simply confusing.

Unless there is no real disadvantage, I would recommend to do things most straight forward.

If you want to create a function, you should be able to use the "function" keyword, as this is what you want the computer to make. But JS provides a bunch of different ways to define functions and sometimes it takes me hours to find out, that the result finally will be a function. Funny, but not efficient...

Collapse
 
codepo8 profile image
Christian Heilmann

It is a great example how hard it is to design a language and how you need to be diligent in adding new features. JavaScript had a few convenience methods added to be like abstraction libraries over the years. This is a problem, as you can't deprecate those. Then again, if you look at PHP, it is worse and yet it powers a lot of the web.

Collapse
 
efpage profile image
Eckehard • Edited

The programming lanuage FORTH was know to regularly win programming contests for real time programming. But it could also happen, that a programmer was not able to understand his own code two weeks after he had written it.

Forth

You can write code in any language, there is a really funny talk about exotic programming languages presented by Join Dylan Beattie, the creator of "Rockstar", that uses Lyrics to write programs.

It is important to see, that a language can have an impact on our programming style, on our productivity and on the maintainability of the code. You can write amazing compact code in Javascript, but this will be as hard to read as assembler. Is this really useful?

We can improve code quality only by adding comments. The same is true if we just use the most simple approach to write programs. It just enhances readability!

Collapse
 
tchaflich profile image
Thomas C. Haflich

JavaScript has the charAt function that accomplishes the same thing:

'beep'.charAt(0); // 'b'
'beep'.charAt(1000); // ''
'🌍'.charAt(0); // \ud83c
Enter fullscreen mode Exit fullscreen mode

With both JS and PHP you also need to be careful about support for multibyte characters.

Collapse
 
shinigami92 profile image
Shinigami

Attention ⚠️

const str = 'abc def'
str[3] !== (str.length > 4)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bkpecho profile image
Bryan King Pecho

Your suggestion of using index existence for checking string length is a neat trick. It not only shortens the code but also adds a readable alternative to using the length property. 👏

Collapse
 
tracker1 profile image
Michael J. Ryan

Now test this out with an emoji in the string to get the emoji character. ;-)