How do I remove the first 100 words from a string? - 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(' ');

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(' ');

Related

I need help getting the first n characters of a string up to when a number character starts

I'm working with a string where I need to extract the first n characters up to where numbers begin. What would be the best way to do this as sometimes the string starts with a number: 7EUSA8889er898 I would need to extract 7EUSA But other string examples would be SWFX74849948, I would need to extract SWFX from that string.
Not sure how to do this with regex my limited knowledge is blocking me at this point:
^(\w{4}) that just gets me the first four characters but I don't really have a stopping point as sometimes the string could be somelongstring292894830982 which would require me to get somelongstring
Using \w will match a word character which includes characters and digits and an underscore.
You could match an optional digit [0-9]? from the start of the string ^and then match 1+ times A-Za-z
^[0-9]?[A-Za-z]+
Regex demo
const regex = /^[0-9]?[A-Za-z]+/;
[
"7EUSA8889er898",
"somelongstring292894830982",
"SWFX74849948"
].forEach(s => console.log(s.match(regex)[0]));
Can use this regex code:
(^\d+?[a-zA-Z]+)|(^\d+|[a-zA-Z]+)
I try with exmaple and good worked:
1- somelongstring292894830982 -> somelongstring
2- 7sdfsdf5456 -> 7sdfsdf
3- 875werwer54556 -> 875werwer
If you want to create function where the RegExp is parametrized by n parameter, this would be
function getStr(str,n) {
var pattern = "\\d?\\w{0,"+n+"}";
var reg = new RegExp(pattern);
var result = reg.exec(str);
if(result[0]) return result[0].substr(0,n);
}
There are answers to this but here is another way to do it.
var string1 = '7EUSA8889er898';
var string2 = 'SWFX74849948';
var Extract = function (args) {
var C = args.split(''); // Split string in array
var NI = []; // Store indexes of all numbers
// Loop through list -> if char is a number add its index
C.map(function (I) { return /^\d+$/.test(I) === true ? NI.push(C.indexOf(I)) : ''; });
// Get the items between the first and second occurence of a number
return C.slice(NI[0] === 0 ? NI[0] + 1 : 0, NI[1]).join('');
};
console.log(Extract(string1));
console.log(Extract(string2));
Output
EUSA
SWFX7
Since it's hard to tell what you are trying to match, I'd go with a general regex
^\d?\D+(?=\d)

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Javascript string replace certain characters

I have this string:
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
I want to repace per_page number (in this case 100, but it can be any number from 1-100, maybe more?)
I can select first part of the string with:
var s1 = s.substr(0, s.lastIndexOf('per_page=')+9)
which give me:
/channels/mtb/videos?page=2&per_page=
but how would I select next '&' after that so I can replace number occurrence?
dont assume same order of parameters!
You can use following regex to replace the content you want.
regex:- /per_page=[\d]*/g(this is only for your requirement)
var new_no=12; //change 100 to 12
var x='/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true';
var y=x.replace(/per_page=[\d]*/g,'per_page='+new_no);
console.log(y);
Explanation:-
/per_page=[\d]*/g
/ ----> is for regex pattern(it inform that from next character onward whatever it encounter will be regex pattern)
per_page= ----> try to find 'per_page=' in string
[\d]* ----> match 0 or more digit (it match until non digit encounter)
/g ---->/ to indicate end of regex pattern and 'g' is for global means find in all string(not only first occurrence)
Use replace with a regular expression to find the numbers after the text per_page=. Like this:
s.replace(/per_page=\d+/,"per_page=" + 33)
Replace the 33 with the number you want.
Result:
"/channels/mtb/videos?page=2&per_page=33&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true"
Start with the index from the lastIndexOf-per_page instead of 0.
Get the index of the first & and create a substr s2 to the end.
Then concat s1 + nr + s2.
I would not use regex, because it is much slower for this simple stuff.
With Array.filter you can do this, where one split the text into key/value pairs, and filter out the one that starts with per_page=.
Stack snippet
var s = '/channels/mtb/videos?page=2&per_page=100&fields=uri%2Cname%2Cdescription%2Cduration%2Cwidth%2Cheight%2Cprivacy%2Cpictures.sizes&sort=date&direction=asc&filter=embeddable&filter_embeddable=true'
var kv_pairs = s.split('&');
var s2 = s.replace((kv_pairs.filter(w => w.startsWith('per_page=')))[0],'per_page=' + 123);
//console.log(s2);
var matches = /(.*\bper_page=)(\d+)(.*)/;
if (matches) {
s = matches[0] + newValue + matches[2];
}

Remove (n)th space from string in JavaScript

I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories