0

I've come across a problem I can't seem to solve. I am setting href on an a using Ajax. data.gameName may be for instance The Witcher 3: Wild Hunt - Blood, Wine and Davis Jr.'s Underpants or perhaps Counter-Strike: Global Offensive. The thing is, example.net only allows a maximum of 40 characters in their searches.

How do I reduce data.gameName, preferrably by cutting words on it's ending till it's 40 characters or less? So that

The Witcher 3: Wild Hunt - Blood, Wine and Davis Jr.'s Underpants

becomes

The Witcher 3: Wild Hunt - Blood, Wine

rather than

The Witcher 3: Wild Hunt - Blood, Wine a?

<span id="hej"><a id="videoLink" href="">This becomes a search link</a></span>
<script>
    $.ajax({
      url: "game.php",
      type: "post",
      async: true,
      dataType: 'json',
      success: function(data){
        $("#hej").find("#videoLink").attr("href",'http://www.example.net/search?q=' + data.gameName);
      /* Cut data.gameName properly here */
      }
    });
</script>

Any hints, tips or guidance will be much appreciated. Thanks in advance.

Algernop K.
  • 477
  • 2
  • 19
  • 1
    You could [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) the string on spaces and then [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) the parts one at a time until the length of the generated string exceeds 40. – showdev Jun 30 '16 at 23:44
  • @showdev Clever! I'll look it up, thanks. So there's not like one ready function for the job, but requires this kind of ingenuity? (I'm a complete scrub, I know) – Algernop K. Jun 30 '16 at 23:46
  • I don't know of a native JavaScript function, but there are [jQuery plugins](https://www.google.com/search?q=jquery+plugin+truncate+text), and [string.js](http://stringjs.com/#methods/truncate-length-chars) provides additional string methods. And here are some [other ideas](http://stackoverflow.com/questions/5454235/javascript-shorten-string-without-cutting-words) on SO. – showdev Jun 30 '16 at 23:52
  • 1
    Ended up going with `replace(/^(.{30}[^\s]*).*/, "$1")` (40 didn't work as I'd hoped for some reason). Thank you very much @showdev! Would you like to put something as an answer so that I can reward you with a "Best answer" note? – Algernop K. Jul 01 '16 at 00:10
  • I appreciate that, but I think its best if [the answer you chose](http://stackoverflow.com/questions/5454235/javascript-shorten-string-without-cutting-words#answer-5454297) gets the credit. Perhaps this question should be marked as a duplicate. – showdev Jul 01 '16 at 00:12
  • @showdev Done! Thanks again, have a good one. – Algernop K. Jul 01 '16 at 00:13
  • http://codepen.io/pen/?editors=1010 – Naga Sai A Jul 01 '16 at 00:22

0 Answers0