How to remove the first 100 words from a string?

I want to delete only the first 100 words and keep the remaining lines.

The code that I have below does the exact opposite:

var short_description = description.split(' ').slice(0,100).join(' '); 
+4
source share
4 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 with slice(x) you will get elements from x to the end of the array. (note: this will return an empty string if the description has less than 100 words.)

Here is some documentation .

You can also use regex:

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

Here is an explanation of the regular expression:

 ^ 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 these 100 words with nothing. (note: if the description is less than 100 words, this regular expression will simply return the description unchanged.)

+15
source
 //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(" ") } 
+1
source
 var short_description = description.split(' ').slice(100).join(' '); 
0
source

The reason this is done in the opposite way is because the slice returns the selected elements (in this case, the first cell) and returns them to its own array. To get all the elements after a hundred, you will need to do something like description.slice (100) to get the distributed array correctly, and then your own union to combine the array.

0
source

Source: https://habr.com/ru/post/1480470/


All Articles