How can I output an array as a scentence except the (1) item? Let's say the content of the array is: ["!report","Jay","This","is","the","reason"];
I tried this to output the items after the (1): (args.slice(1));however the output now is: "This,is,the,reason", how could I make it output as a normal scentence?
If you don't want to use built in methods, you can append each word
in the array starting at index 1 (second item).
// List of words
var words = ["!report","Jay","This","is","the","reason"];
// Empty string
var sentence = "";
// Loop through array starting at index 1 (second item)
for (let i = 1; i < words.length; i++) {
// Keep appending the words to sentence string
sentence = sentence + words[i] + " ";
}
// Print the sentence as a whole
console.log(sentence);
Or using built in functions:
// Array of strings
var array = ["!report","Jay","This","is","the","reason"];
// Cut off the first element, words is still an array though
var words = array.slice(1)
// Join each element into a string with spaces in between
var sentence = words.join(" ")
// Print as full sentence
console.log(sentence)
Output:
"Jay This is the reason"
You could slice from the second element and join the array.
console.log(["!report","Jay","This","is","the","reason"].slice(2).join(' '));
.slice() returns a new array, so when you access it as a whole, you often see a comma separated list of the array values.
But, .slice() along with .join() does the trick. .join() allows you to "join" all the array values as a single string. If you pass an argument to .join(), that argument will be used as a separator.
You can then just concatenate a period (.) to the end of the string.
console.log(["!report","Jay","This","is","the","reason"].slice(1).join(" ") + ".");
The output you desire is not very clear (do you want to remove only the first item or also the second). However the methods are the same:
you can use destructuring assignment syntax if you're es6 compliant
const arr = [a,b,...c] = ["!report","Jay","This","is","the","reason"];
let sentence = c.join(" ");
// or
let sentence2 = c.toString().replace(/,/g," ");
console.log (sentence," - ",sentence2);
or simply replace with regex and a correct pattern
const arr = ["!report","Jay","This","is","the","reason"];
let sentence = arr.toString().replace(/^[A-z! ]+?,[A-z ]+?,/,"").replace(/,/g," ");
// or
let sentence2 = arr.toString().replace(/^[A-z! ]+?,/,"").replace(/,/g," ");
console.log (sentence," - ",sentence2);
Here it is, check fiddle comments for code explanation.
var a = ["!report","Jay","This","is","the","reason"];
//removes first element from array and implodes array with spaces
var sentence = a.slice(1).join(" ");
console.log(sentence);
Related
i've searched a lot but havent found exactly what i am trying to do. But here goes:
I want to input a sentence / string in javascript and output all randomized variations of that sentence.
Example
input: 'my test sentence 123'
output: 'test my sentence 123', 'my sentence 123 test', '123 sentence my test', and so on, and stop when theres no variations left.
I've split the sentence into words in an array, but im a bit stuck on how to proceed to randomize the words and join them to new sentences in a list or new array.
code so far:
let str = "my test sentence 123";
let words = str.split(" ");
for (let i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
A bit stuck on how to proceed. My thought process is: I have the words variable / array, but i need to randomize each word, output new strings but also check the existing ones so i don't duplicate any of them.
Thanks for all help i can get to learn more :)
Check this code
var phrase = "my test sentence 123";
var words = phrase.toLowerCase().match(/\w+/g);
var wordsCopy = phrase.toLowerCase().match(/\w+/g);
// First of all I loop each word
words.forEach(function(word, index){
// Random word going to contain my randomized word
var randomWord = word;
// Copy the entire phrase
var wordsMissing = wordsCopy.slice();
// Remove the current word
wordsMissing.splice(wordsCopy.indexOf(word), 1);
// Loop tru my missing words
for (var i = 0; i < wordsMissing.length; i++) {
// Set my random word with the rest of the words
randomWord += " " + wordsMissing.join(" ");
// get the first word and send to the final of my original phrase
var firstWord = wordsMissing.splice(0,1)[0];
wordsMissing.push(firstWord);
// Log my random word
console.log(randomWord);
// Reset random word to the initial word
randomWord = word;
}
});
As you are on Javascript, using .join(' ') will be easier to create a string from an array.
Then, there is a lot of solutions to achieve what you want to do, the easier way would be a foreach on foreach, where you simply test if the string you created already exists in the array.
It would be the easy way, but the more you put items, the more you will need power, so use this solution wisely.
Something like this can work :
var stringToSplit = 'I want to split this'
var stringSplitted = stringToSplit.split(' ')
var arrayOfNewStrings = []
stringSplitted.forEach(word => {
var arrayOfString = []
arrayOfString.push(word)
stringSplitted.forEach(otherWord => {
if(word !== otherWord)
arrayOfString.push(otherWord)
})
arrayOfNewStrings.push(arrayOfString)
});
console.log(arrayOfNewStrings)
You then need to add a layer of for/foreach to make it for every words (this will work only for the first one), and to test if the array already exists in ArrayOfNewStrings to prevent duplication.
When I utilise the slice method like so:
"Hello".slice(0,-1);
The result I get will be "Hell". Then if I run through that again using the same code, I will get "Hel".
Is there a way that I can extract and store into a variable the actual character that was sliced off, in this case "H" or on the second run "e", and not just the remainder of the string?
You could just use a second .slice() on the original string.
For example, where "Hello".slice(0,-1); returns all but the last character, "Hello".slice(-1) returns only the last character.
var input = "Hello";
var removed = input.slice(-1); // "o"
var remaining = input.slice(0, -1); // "Hell"
I don't think there's a more generic solution than that, because .slice() also lets you extract the middle of a string, in which case you'd need two extra calls to get the two parts being removed.
Demo:
var input = "Hello";
var allRemoved = [];
var removed;
while (input != "") {
allRemoved.push(removed = input.slice(-1));
input = input.slice(0, -1);
console.log("'" + removed + "' removed, leaving '" + input + "'");
}
console.log("Removed: " + allRemoved.join(", "));
Alternatively, if you only care about removing characters one at a time, you could forget about .slice() and instead convert the string to an array and use .shift() or .pop() to remove the character at the beginning or end respectively:
var input = "Hello";
var inArr = input.split("");
while (inArr.length > 0) {
console.log(inArr.pop());
}
This might not be the most efficient way to do this but you can turn yout string as an array with .split, then use .splice to remove certain elements ( letters ) and store them as a variable. Finally you turn your variable of removed letters back to a string using .join
let name = 'David'
let arrayname = name.split('')
let chosenLetters = arrayname.splice(0,2)
let finalLetters = chosenLetters.join('')
console.log(finalLetters) //should output Da
For split and join I recommend you leave the argument as (''). For .splice you can find in the docs for js how to select specific letters. In my example I am saying "Start at index 0 and cut the first 2 elements". Splice has many other ways to select an index so I recommend you read the docs.
In one line of code it can be generalized to :
let name = 'David'
let finalLetters = name.split('').splice(0,2).join('')
console.log(finalLetters) //should output Da
I'm working through a problem on freecodecamp.com, and I want to see whether my code so far is doing what I think it is doing...
function titleCase(str) {
var wordArr = str.split(' '); // now the sentences is an array of words
for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
charArr = wordArr[i].split(''); //charArr is a 2D array of characters within words?
return charArr[1][1];
}
}
titleCase("a little tea pot"); // this should give me 'i', right?
Again, this is just the beginning of the code. My goal is to capitalize the first letter of each word in the parameter of titleCase();. Perhaps I'm not even going about this right at all.
But... is charArr on line 4 a multidimensional array. Did that create [['a'],['l','i','t','t','l','e'],['t','e','a','p','o','t']]?
In addition to ABR answer (I can't comment yet) :
charArr is a one-dimensional array, if you want it to be a 2d array you need to push the result of wordArr[i].split(''); instead of assigning it.
charArr.push(wordArr[i].split(''));
And don't forget to initialize charArr as an empty array
Few issues :
1. Your return statement will stop this after one iteration.
2. If one of the words have fewer then 2 letters (like the first one in your example, which is 'a') - you will get an exception at charArr[1][1].
Other then that, it is mostly ok.
It would probably help you to download a tool like firebug and test your code live...
You can do the following:
function titleCase(str) {
var newString = "";
var wordArr = str.split(' ');
for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
var firstLetter = wordArr[i].slice(0,1); // get the first letter
//capitalize the first letter and attach the rest of the word
newString += firstLetter.toUpperCase() + wordArr[i].substring(1) + " ";
}
return newString;
}
Also you need to remove the return statement in your for loop because the first time the for loop goes over the return statement, it will end the function and you will not be able to loop through all the words
Here you can learn more about string.slice() : http://www.w3schools.com/jsref/jsref_slice_string.asp
I want to add a letter (any letter, lets say p) to the end of every word using regular javascript but im not sure how to do this.
I already have this incomplete code.
var y = prompt("type a sentence here!"); //person types in sentence that will get changed//
function funkyfunction() {
for(var i=0;i<x.length;i++){
if(x.charAt(i)==" "){
}
}
};
funkyfunction(); //would call the function and print the result
You could use split, which will split a string on each occurrence of the character you provide it and return an array.
So "Type a sentence here".split(" ") would return ["Type", "a", "sentence", "here"].
You could then iterate over that array and add a character to the end of each element!
Then use join to convert the array back into a string. Make sure you pass join the right separator!
Building on the last answer the specifics on how to join them together would be something like this
var x = prompt("type a sentence here!"); //person types in sentence that will get changed//
function funkyfunction()
{
var words = x.split(" ");
for (var i = 0; i < words.length; i++) {
words[i] += "p";
}
x = words.join(" ");
console.log(x); // or alert(x); which ever is most useful
}
funkyfunction(); //would call the function and print the result
As you can see we split the string into an array by the delimiter of space to get an array of words, then we loop through the items in the array and just add p to the end of it. at the end we set the original variable equal to the array combined back together with the spaces added back.
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(' ');