最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I remove the first 100 words from a string? - Stack Overflow

programmeradmin2浏览0评论

I only want to remove the first 100 words and keep whats remaining from the string.

The code I have below does the exact opposite:

   var short_description = description.split(' ').slice(0,100).join(' ');

I only want to remove the first 100 words and keep whats remaining from the string.

The code I have below does the exact opposite:

   var short_description = description.split(' ').slice(0,100).join(' ');
Share Improve this question asked May 13, 2013 at 12:19 Malcr001Malcr001 8,28910 gold badges46 silver badges57 bronze badges 4
  • Did you look at some doco for .slice()? – nnnnnn Commented May 13, 2013 at 12:21
  • I did wrong in my answer, but this page will help you – Grijesh Chauhan Commented May 13, 2013 at 12:24
  • 1 @GrijeshChauhan - No, that page is about the String functions. OP needs the Array .slice(). – nnnnnn Commented May 13, 2013 at 12:26
  • @nnnnnn ok that is the reason my answer was wrong, thanks :) – Grijesh Chauhan Commented May 13, 2013 at 12:28
Add a comment  | 

4 Answers 4

Reset to default 22

Remove the first argument:

var short_description = description.split(' ').slice(100).join(' ');

Using slice(x, y) will give you elements from x to y, but using slice(x) will give you elements from x to the end of the array. (note: this will return the empty string if the description has less than 100 words.)

Here is some documentation.

You could also use a regex:

var short_description = description.replace(/^([^ ]+ ){100}/, '');

Here is an explanation of the regex:

^      beginning of string
(      start a group
[^ ]   any character that is not a space
+      one or more times
       then a space
)      end the group. now the group contains a word and a space.
{100}  100 times

Then replace those 100 words with nothing. (note: if the description is less than 100 words, this regex will just return the description unchanged.)

//hii i am getting result using this function   


 var inputString = "This is           file placed  on           Desktop"
    inputString = removeNWords(inputString, 2)
    console.log(inputString);
    function removeNWords(input,n) {
      var newString = input.replace(/\s+/g,' ').trim();
      var x = newString.split(" ")
      return x.slice(n,x.length).join(" ")
    }

The reason this is doing the opposite, is that slice returns the selected elements (in this case, the first one hundred) and returns them in it's own array. To get all of the elements after one hundred, you would have to do something like description.slice(100) to get the split array properly, and then your own join to merge back the array.

var short_description = description.split(' ').slice(100).join(' ');
发布评论

评论列表(0)

  1. 暂无评论