Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the first 100 words from a string?

Tags:

javascript

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(' ');
like image 834
Malcr001 Avatar asked May 13 '13 12:05

Malcr001


People also ask

How do you delete one text from a string?

To remove a character from a string, use string replace() and regular expression. This combination is used to remove all occurrences of the particular character, unlike the previous function. A regular expression is used instead of a string along with global property.

How do I remove the first word from a string in R?

Use the stringr Package in R. The stringr package provides the str_sub() function to remove the first character from a string.


2 Answers

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.)

like image 51
tckmn Avatar answered Oct 04 '22 01:10

tckmn


//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(" ")
    }
like image 44
Abhishek Priyadarshi Avatar answered Oct 04 '22 01:10

Abhishek Priyadarshi