JavaScript Coding Challenge #8

This challenge was pretty short, but it was fun to play with!
I hope you enjoy it!

1 Like

Nice solution.

There’s just one thing. If a letter in word is not found, you’ll still going to check the other letters but it’s not necessary.
Here’s my version which exits as soon as a letter is not found:

function occ2(str, word) {
    let idx = 0;
    for (let i=0,l=word.length; i<l; i++) {
      // make sure we search after the previous letter by passing idx as second param
      idx = str.indexOf(word[i], idx);
      if (idx === -1) {
        return false
    return true

You also do not need to split str into an array as indexOf is also available for String objects.

Hope this helps.

1 Like

Very nice solution @JoolsMcFly !
I just learned today I can pass a second argument for the indexOf method.
Thanks! :smiley:
If you want, you could also post the answer in the comments section on medium. This way other readers can find it easily there too :slight_smile:

You’re right. I’ll do that then. Cheers.

Found another shorter solution while stretching. You just never know when ideas pop, eh?

function Test (s, w) {
  var pattern = w.replace(/./g, function(char) {
    return char + '.*';
  }).slice(0, -2); // remove trailing .*
  return RegExp(pattern)) !== -1;

I have not benchmarked it but it’s showcasing an alternative, non array-based approach.

1 Like

To be honest RegExp is something I need to look into more :smiley:
I’d love to write a follow up for the article with your code if you allow me to do so of course! :slight_smile:

Thank you @JoolsMcFly for this amazing solution! I love it! :heart:

You can include both solutions, np.

1 Like

@JoolsMcFly here you can find the follow up:

Thank you again! :slight_smile:

Cool stuff, well presented.

One correction is needed though.

If the word is medium the pattern will be: w.*o.*r.*d.*

Pattern would be m.*e.*d.*i.*u.*m.* in this case.

Onto the next one! :slight_smile:

1 Like

Thank you for the correction! :wink: