Cropping a message using array splitsMilliseconds to Time string & Time string to MillisecondsVarious simple JavaScript solutionsDefinitional Returns. Solved. MostlyBaking homemade pies has made me so many new connectionsA String.prototype.diff() implementation (text diff)Simple Java password rule enforcingSmall JavaScript library for ECMAScript version detectionThis macro will convert you… or notApproximate string search in PythonImporting text into PANDAS and counting certain words

Why is the Sun made of light elements only?

Why is PerfectForwardSecrecy considered OK, when it has same defects as salt-less password hashing?

How to select certain lines (n, n+4, n+8, n+12...) from the file?

Are there variations of the regular runtimes of the Big-O-Notation?

How to efficiently lower your karma

No such column 'DeveloperName' on entity 'RecordType' after Summer '19 release on sandbox

My perfect evil overlord plan... or is it?

A Cunning Riley Riddle

Cropping a message using array splits

Succinct and gender-neutral Russian word for "writer"

If a character drops a magic item that turns on/off, does that item turn off when they drop it?

Ex-manager wants to stay in touch, I don't want to

Was Mohammed the most popular first name for boys born in Berlin in 2018?

What do "KAL." and "A.S." stand for in this inscription?

Is ‘despite that’ right?

Is there any evidence to support the claim that the United States was "suckered into WW1" by Zionists, made by Benjamin Freedman in his 1961 speech

Should I pay on student loans in deferment or continue to snowball other debts?

Has there been evidence of any other gods?

How can I avoid subordinates and coworkers leaving work until the last minute, then having no time for revisions?

Examples where existence is harder than evaluation

Is this state of Earth possible, after humans left for a million years?

Is it a Munchausen Number?

Cryptography and elliptic curves

Was there a contingency plan in place if Little Boy failed to detonate?



Cropping a message using array splits


Milliseconds to Time string & Time string to MillisecondsVarious simple JavaScript solutionsDefinitional Returns. Solved. MostlyBaking homemade pies has made me so many new connectionsA String.prototype.diff() implementation (text diff)Simple Java password rule enforcingSmall JavaScript library for ECMAScript version detectionThis macro will convert you… or notApproximate string search in PythonImporting text into PANDAS and counting certain words






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5












$begingroup$


I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.



Example:



Input String: The quick brown fox jumped over the fence, K: 11



Output: The quick



Here is what I have tried:



 function crop(message, K) 
var originalLen = message.length;
if(originalLen<K)

return message;

else

var words = message.split(' '),substr;

for(var i=words.length;i > 0;i--)


words.pop();

if(words.join(' ').length<=K)

return words.join(' ');








This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?










share|improve this question











$endgroup$


















    5












    $begingroup$


    I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.



    Example:



    Input String: The quick brown fox jumped over the fence, K: 11



    Output: The quick



    Here is what I have tried:



     function crop(message, K) 
    var originalLen = message.length;
    if(originalLen<K)

    return message;

    else

    var words = message.split(' '),substr;

    for(var i=words.length;i > 0;i--)


    words.pop();

    if(words.join(' ').length<=K)

    return words.join(' ');








    This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?










    share|improve this question











    $endgroup$














      5












      5








      5





      $begingroup$


      I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.



      Example:



      Input String: The quick brown fox jumped over the fence, K: 11



      Output: The quick



      Here is what I have tried:



       function crop(message, K) 
      var originalLen = message.length;
      if(originalLen<K)

      return message;

      else

      var words = message.split(' '),substr;

      for(var i=words.length;i > 0;i--)


      words.pop();

      if(words.join(' ').length<=K)

      return words.join(' ');








      This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?










      share|improve this question











      $endgroup$




      I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.



      Example:



      Input String: The quick brown fox jumped over the fence, K: 11



      Output: The quick



      Here is what I have tried:



       function crop(message, K) 
      var originalLen = message.length;
      if(originalLen<K)

      return message;

      else

      var words = message.split(' '),substr;

      for(var i=words.length;i > 0;i--)


      words.pop();

      if(words.join(' ').length<=K)

      return words.join(' ');








      This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?







      javascript performance strings array formatting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 1 hour ago









      200_success

      132k20159426




      132k20159426










      asked 8 hours ago









      beNerdbeNerd

      1373




      1373




















          3 Answers
          3






          active

          oldest

          votes


















          5












          $begingroup$

          This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number.



          In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.



          A regular expression is an efficient and compact way to find text that meets your criteria. Consider:



          function crop(message, K) 


          .match returns an array with the matched text as the first element, or null if no match. The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).



          The regular expression, broken down, means:




          • ^: match start of string


          • .: followed by any character


          • 0,10: ... up to ten times (one less than K)


          • [^ ]: followed by a character that is not a space


          • (?=…): this is an assertion; it means the following expression must match, but is not included in the result:


            • : followed by a space


            • |: or


            • $: end-of-string


          Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?






          share|improve this answer









          $endgroup$












          • $begingroup$
            Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
            $endgroup$
            – Peilonrayz
            2 hours ago











          • $begingroup$
            /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
            $endgroup$
            – Oh My Goodness
            2 hours ago










          • $begingroup$
            Ah, that makes sense. Thank you :)
            $endgroup$
            – Peilonrayz
            2 hours ago


















          3












          $begingroup$

          Your code looks great.




          Oh My Goodness's solution is really great.





          If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so:



          ([A-z0-9s]1,11)(s)(.*)


          This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list.



          You may also want to add or reduce the boundaries.



          enter image description here



          Graph



          This graph shows how the expression would work and you can visualize other expressions in this link:



          enter image description here



          Performance Test



          This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.






          const repeat = 1000000;
          const start = Date.now();

          for (var i = repeat; i >= 0; i--)
          const string = 'The quick brown fox jumped over the fence';
          const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
          var match = string.replace(regex, "$1");


          const end = Date.now() - start;
          console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
          console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





          Testing Code






          const regex = /([A-z0-9s]1,11)(s)(.*)/s;
          const str = `The quick brown fox jumped over the fence`;
          const subst = `$1`;

          // The substituted value will be contained in the result variable
          const result = str.replace(regex, subst);

          console.log('Substitution result: ', result);








          share|improve this answer











          $endgroup$








          • 1




            $begingroup$
            FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
            $endgroup$
            – Peilonrayz
            2 hours ago











          • $begingroup$
            @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
            $endgroup$
            – Emma
            2 hours ago






          • 1




            $begingroup$
            I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
            $endgroup$
            – Peilonrayz
            2 hours ago










          • $begingroup$
            @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
            $endgroup$
            – Emma
            2 hours ago


















          2












          $begingroup$

          A Code Review



          Your code is a mess,



          • Inconsistent indenting.

          • Poor use of space between tokens, and operators.

          • Inappropriate use of variable declaration type let, var, const.

          • Contains irrelevant / unused code. eg substr

          Fails to meet requirements.



          You list the requirement




          "no trailing spaces in the end."




          Yet your code fails to do this in two ways



          When string is shorter than required length



           crop("trailing spaces ", 100); // returns "trailing spaces "


          When string contains 2 or more spaces near required length.



           crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "


          Note: There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg "👨‍🚀".length === 5 is true. All JavaScript strings are Unicode.



          Rewrite



          Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.



          I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)



          I assume that the message was converted from ASCII and spaces are the only white spaces of concern.



          function crop(message, maxLength) { // use meaningful names
          var result = message.trimEnd(); // Use var for function scoped variable
          if (result.length > maxLength) // space between if ( > and )
          const words = result.split(" "); // use const for variables that do not change
          do
          words.pop();
          result = words.join(" ").trimEnd(); // ensure no trailing spaces
          if (result.length <= maxLength) // not repeating same join operation
          break;

          while (words.length);

          return result;



          Note: Check runtime has String.trimEnd or use a polyfill or transpiler.






          share|improve this answer









          $endgroup$













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220011%2fcropping-a-message-using-array-splits%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5












            $begingroup$

            This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number.



            In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.



            A regular expression is an efficient and compact way to find text that meets your criteria. Consider:



            function crop(message, K) 


            .match returns an array with the matched text as the first element, or null if no match. The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).



            The regular expression, broken down, means:




            • ^: match start of string


            • .: followed by any character


            • 0,10: ... up to ten times (one less than K)


            • [^ ]: followed by a character that is not a space


            • (?=…): this is an assertion; it means the following expression must match, but is not included in the result:


              • : followed by a space


              • |: or


              • $: end-of-string


            Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?






            share|improve this answer









            $endgroup$












            • $begingroup$
              Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
              $endgroup$
              – Oh My Goodness
              2 hours ago










            • $begingroup$
              Ah, that makes sense. Thank you :)
              $endgroup$
              – Peilonrayz
              2 hours ago















            5












            $begingroup$

            This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number.



            In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.



            A regular expression is an efficient and compact way to find text that meets your criteria. Consider:



            function crop(message, K) 


            .match returns an array with the matched text as the first element, or null if no match. The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).



            The regular expression, broken down, means:




            • ^: match start of string


            • .: followed by any character


            • 0,10: ... up to ten times (one less than K)


            • [^ ]: followed by a character that is not a space


            • (?=…): this is an assertion; it means the following expression must match, but is not included in the result:


              • : followed by a space


              • |: or


              • $: end-of-string


            Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?






            share|improve this answer









            $endgroup$












            • $begingroup$
              Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
              $endgroup$
              – Oh My Goodness
              2 hours ago










            • $begingroup$
              Ah, that makes sense. Thank you :)
              $endgroup$
              – Peilonrayz
              2 hours ago













            5












            5








            5





            $begingroup$

            This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number.



            In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.



            A regular expression is an efficient and compact way to find text that meets your criteria. Consider:



            function crop(message, K) 


            .match returns an array with the matched text as the first element, or null if no match. The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).



            The regular expression, broken down, means:




            • ^: match start of string


            • .: followed by any character


            • 0,10: ... up to ten times (one less than K)


            • [^ ]: followed by a character that is not a space


            • (?=…): this is an assertion; it means the following expression must match, but is not included in the result:


              • : followed by a space


              • |: or


              • $: end-of-string


            Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?






            share|improve this answer









            $endgroup$



            This is much slower than necessary. It takes time to construct the array, and more to shorten the array word-by-word. It's easy to imagine how this would go if words contains a whole book and K is some small number.



            In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.



            A regular expression is an efficient and compact way to find text that meets your criteria. Consider:



            function crop(message, K) 


            .match returns an array with the matched text as the first element, or null if no match. The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K).



            The regular expression, broken down, means:




            • ^: match start of string


            • .: followed by any character


            • 0,10: ... up to ten times (one less than K)


            • [^ ]: followed by a character that is not a space


            • (?=…): this is an assertion; it means the following expression must match, but is not included in the result:


              • : followed by a space


              • |: or


              • $: end-of-string


            Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 7 hours ago









            Oh My GoodnessOh My Goodness

            2,657315




            2,657315











            • $begingroup$
              Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
              $endgroup$
              – Oh My Goodness
              2 hours ago










            • $begingroup$
              Ah, that makes sense. Thank you :)
              $endgroup$
              – Peilonrayz
              2 hours ago
















            • $begingroup$
              Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
              $endgroup$
              – Oh My Goodness
              2 hours ago










            • $begingroup$
              Ah, that makes sense. Thank you :)
              $endgroup$
              – Peilonrayz
              2 hours ago















            $begingroup$
            Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
            $endgroup$
            – Peilonrayz
            2 hours ago





            $begingroup$
            Why do you have [^ ]? When thinking of what the answer would be I got /^.1,11(?=s)/ yours is better as it check for $ too. But I can't understand the addition of [^ ].
            $endgroup$
            – Peilonrayz
            2 hours ago













            $begingroup$
            /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
            $endgroup$
            – Oh My Goodness
            2 hours ago




            $begingroup$
            /^.1,11(?=s)/ will include a trailing space in the match if there are two spaces together.
            $endgroup$
            – Oh My Goodness
            2 hours ago












            $begingroup$
            Ah, that makes sense. Thank you :)
            $endgroup$
            – Peilonrayz
            2 hours ago




            $begingroup$
            Ah, that makes sense. Thank you :)
            $endgroup$
            – Peilonrayz
            2 hours ago













            3












            $begingroup$

            Your code looks great.




            Oh My Goodness's solution is really great.





            If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so:



            ([A-z0-9s]1,11)(s)(.*)


            This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list.



            You may also want to add or reduce the boundaries.



            enter image description here



            Graph



            This graph shows how the expression would work and you can visualize other expressions in this link:



            enter image description here



            Performance Test



            This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.






            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            Testing Code






            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);








            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
              $endgroup$
              – Emma
              2 hours ago






            • 1




              $begingroup$
              I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
              $endgroup$
              – Peilonrayz
              2 hours ago










            • $begingroup$
              @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
              $endgroup$
              – Emma
              2 hours ago















            3












            $begingroup$

            Your code looks great.




            Oh My Goodness's solution is really great.





            If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so:



            ([A-z0-9s]1,11)(s)(.*)


            This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list.



            You may also want to add or reduce the boundaries.



            enter image description here



            Graph



            This graph shows how the expression would work and you can visualize other expressions in this link:



            enter image description here



            Performance Test



            This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.






            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            Testing Code






            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);








            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
              $endgroup$
              – Emma
              2 hours ago






            • 1




              $begingroup$
              I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
              $endgroup$
              – Peilonrayz
              2 hours ago










            • $begingroup$
              @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
              $endgroup$
              – Emma
              2 hours ago













            3












            3








            3





            $begingroup$

            Your code looks great.




            Oh My Goodness's solution is really great.





            If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so:



            ([A-z0-9s]1,11)(s)(.*)


            This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list.



            You may also want to add or reduce the boundaries.



            enter image description here



            Graph



            This graph shows how the expression would work and you can visualize other expressions in this link:



            enter image description here



            Performance Test



            This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.






            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            Testing Code






            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);








            share|improve this answer











            $endgroup$



            Your code looks great.




            Oh My Goodness's solution is really great.





            If you wish, you might be able to design an expression that would do the entire process. I'm not so sure about my expression in this link, but it might give you an idea, how you may do so:



            ([A-z0-9s]1,11)(s)(.*)


            This expression is relaxed from the right and has three capturing groups with just a list of chars that I have just added in the first capturing group and I'm sure you might want to change that list.



            You may also want to add or reduce the boundaries.



            enter image description here



            Graph



            This graph shows how the expression would work and you can visualize other expressions in this link:



            enter image description here



            Performance Test



            This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.






            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            Testing Code






            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);








            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            const repeat = 1000000;
            const start = Date.now();

            for (var i = repeat; i >= 0; i--)
            const string = 'The quick brown fox jumped over the fence';
            const regex = /([A-z0-9s]1,11)(s)(.*)/gm;
            var match = string.replace(regex, "$1");


            const end = Date.now() - start;
            console.log("YAAAY! "" + match + "" is a match 💚💚💚 ");
            console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");





            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);





            const regex = /([A-z0-9s]1,11)(s)(.*)/s;
            const str = `The quick brown fox jumped over the fence`;
            const subst = `$1`;

            // The substituted value will be contained in the result variable
            const result = str.replace(regex, subst);

            console.log('Substitution result: ', result);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 5 hours ago

























            answered 6 hours ago









            EmmaEmma

            2551215




            2551215







            • 1




              $begingroup$
              FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
              $endgroup$
              – Emma
              2 hours ago






            • 1




              $begingroup$
              I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
              $endgroup$
              – Peilonrayz
              2 hours ago










            • $begingroup$
              @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
              $endgroup$
              – Emma
              2 hours ago












            • 1




              $begingroup$
              FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
              $endgroup$
              – Peilonrayz
              2 hours ago











            • $begingroup$
              @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
              $endgroup$
              – Emma
              2 hours ago






            • 1




              $begingroup$
              I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
              $endgroup$
              – Peilonrayz
              2 hours ago










            • $begingroup$
              @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
              $endgroup$
              – Emma
              2 hours ago







            1




            1




            $begingroup$
            FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
            $endgroup$
            – Peilonrayz
            2 hours ago





            $begingroup$
            FWIW I found (/^.1,11(?=s)/gm).exec(string)[0] to be much faster. (FF) I also think it's simpler, but given there's a forward reference I can see why others might not agree.
            $endgroup$
            – Peilonrayz
            2 hours ago













            $begingroup$
            @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
            $endgroup$
            – Emma
            2 hours ago




            $begingroup$
            @Peilonrayz Hi there, Sure thing! Your expression is much better! Thanks so much for the advice!
            $endgroup$
            – Emma
            2 hours ago




            1




            1




            $begingroup$
            I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
            $endgroup$
            – Peilonrayz
            2 hours ago




            $begingroup$
            I saw a performance test and the urge to try it out over came me, looking at the other answer it's a slightly worse version than Oh My Goodness'. Nice answer btw :)
            $endgroup$
            – Peilonrayz
            2 hours ago












            $begingroup$
            @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
            $endgroup$
            – Emma
            2 hours ago




            $begingroup$
            @Peilonrayz Thanks so much! Sure thing! Oh My Goodness answers are really great!
            $endgroup$
            – Emma
            2 hours ago











            2












            $begingroup$

            A Code Review



            Your code is a mess,



            • Inconsistent indenting.

            • Poor use of space between tokens, and operators.

            • Inappropriate use of variable declaration type let, var, const.

            • Contains irrelevant / unused code. eg substr

            Fails to meet requirements.



            You list the requirement




            "no trailing spaces in the end."




            Yet your code fails to do this in two ways



            When string is shorter than required length



             crop("trailing spaces ", 100); // returns "trailing spaces "


            When string contains 2 or more spaces near required length.



             crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "


            Note: There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg "👨‍🚀".length === 5 is true. All JavaScript strings are Unicode.



            Rewrite



            Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.



            I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)



            I assume that the message was converted from ASCII and spaces are the only white spaces of concern.



            function crop(message, maxLength) { // use meaningful names
            var result = message.trimEnd(); // Use var for function scoped variable
            if (result.length > maxLength) // space between if ( > and )
            const words = result.split(" "); // use const for variables that do not change
            do
            words.pop();
            result = words.join(" ").trimEnd(); // ensure no trailing spaces
            if (result.length <= maxLength) // not repeating same join operation
            break;

            while (words.length);

            return result;



            Note: Check runtime has String.trimEnd or use a polyfill or transpiler.






            share|improve this answer









            $endgroup$

















              2












              $begingroup$

              A Code Review



              Your code is a mess,



              • Inconsistent indenting.

              • Poor use of space between tokens, and operators.

              • Inappropriate use of variable declaration type let, var, const.

              • Contains irrelevant / unused code. eg substr

              Fails to meet requirements.



              You list the requirement




              "no trailing spaces in the end."




              Yet your code fails to do this in two ways



              When string is shorter than required length



               crop("trailing spaces ", 100); // returns "trailing spaces "


              When string contains 2 or more spaces near required length.



               crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "


              Note: There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg "👨‍🚀".length === 5 is true. All JavaScript strings are Unicode.



              Rewrite



              Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.



              I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)



              I assume that the message was converted from ASCII and spaces are the only white spaces of concern.



              function crop(message, maxLength) { // use meaningful names
              var result = message.trimEnd(); // Use var for function scoped variable
              if (result.length > maxLength) // space between if ( > and )
              const words = result.split(" "); // use const for variables that do not change
              do
              words.pop();
              result = words.join(" ").trimEnd(); // ensure no trailing spaces
              if (result.length <= maxLength) // not repeating same join operation
              break;

              while (words.length);

              return result;



              Note: Check runtime has String.trimEnd or use a polyfill or transpiler.






              share|improve this answer









              $endgroup$















                2












                2








                2





                $begingroup$

                A Code Review



                Your code is a mess,



                • Inconsistent indenting.

                • Poor use of space between tokens, and operators.

                • Inappropriate use of variable declaration type let, var, const.

                • Contains irrelevant / unused code. eg substr

                Fails to meet requirements.



                You list the requirement




                "no trailing spaces in the end."




                Yet your code fails to do this in two ways



                When string is shorter than required length



                 crop("trailing spaces ", 100); // returns "trailing spaces "


                When string contains 2 or more spaces near required length.



                 crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "


                Note: There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg "👨‍🚀".length === 5 is true. All JavaScript strings are Unicode.



                Rewrite



                Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.



                I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)



                I assume that the message was converted from ASCII and spaces are the only white spaces of concern.



                function crop(message, maxLength) { // use meaningful names
                var result = message.trimEnd(); // Use var for function scoped variable
                if (result.length > maxLength) // space between if ( > and )
                const words = result.split(" "); // use const for variables that do not change
                do
                words.pop();
                result = words.join(" ").trimEnd(); // ensure no trailing spaces
                if (result.length <= maxLength) // not repeating same join operation
                break;

                while (words.length);

                return result;



                Note: Check runtime has String.trimEnd or use a polyfill or transpiler.






                share|improve this answer









                $endgroup$



                A Code Review



                Your code is a mess,



                • Inconsistent indenting.

                • Poor use of space between tokens, and operators.

                • Inappropriate use of variable declaration type let, var, const.

                • Contains irrelevant / unused code. eg substr

                Fails to meet requirements.



                You list the requirement




                "no trailing spaces in the end."




                Yet your code fails to do this in two ways



                When string is shorter than required length



                 crop("trailing spaces ", 100); // returns "trailing spaces "


                When string contains 2 or more spaces near required length.



                 crop("Trailing spaces strings with extra spaces", 17); // returns "Trailing spaces "


                Note: There are various white space characters not just the space. There are also special unicode characters the are visually 1 character (depending on device OS) yet take up 2 or more characters. eg "👨‍🚀".length === 5 is true. All JavaScript strings are Unicode.



                Rewrite



                Using the same logic (build return string from array of split words) the following example attempts to correct the style and adherence to the requirements.



                I prefer 4 space indentation (using spaces not tabs as tabs always seem to stuff up when copying between systems) however 2 spaces is acceptable (only by popularity)



                I assume that the message was converted from ASCII and spaces are the only white spaces of concern.



                function crop(message, maxLength) { // use meaningful names
                var result = message.trimEnd(); // Use var for function scoped variable
                if (result.length > maxLength) // space between if ( > and )
                const words = result.split(" "); // use const for variables that do not change
                do
                words.pop();
                result = words.join(" ").trimEnd(); // ensure no trailing spaces
                if (result.length <= maxLength) // not repeating same join operation
                break;

                while (words.length);

                return result;



                Note: Check runtime has String.trimEnd or use a polyfill or transpiler.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 3 hours ago









                Blindman67Blindman67

                10.6k1623




                10.6k1623



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220011%2fcropping-a-message-using-array-splits%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Log på Navigationsmenu

                    Wonderful Copenhagen (sang) Eksterne henvisninger | NavigationsmenurSide på frankloesser.comWonderful Copenhagen

                    Detroit Tigers Spis treści Historia | Skład zespołu | Sukcesy | Członkowie Baseball Hall of Fame | Zastrzeżone numery | Przypisy | Menu nawigacyjneEncyclopedia of Detroit - Detroit TigersTigers Stadium, Detroit, MITigers Timeline 1900sDetroit Tigers Team History & EncyclopediaTigers Timeline 1910s1935 World Series1945 World Series1945 World Series1984 World SeriesComerica Park, Detroit, MI2006 World Series2012 World SeriesDetroit Tigers 40-Man RosterDetroit Tigers Coaching StaffTigers Hall of FamersTigers Retired Numberse