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.
Related
I Have the function WordSplit(strArr) which has to read the array of strings stored in strArr, which will contain 2 elements: the first element will be a sequence of characters, and the second element will be a long string of comma-separated words, in alphabetical order, that represents a dictionary of some arbitrary length.
For example: strArr can be: ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]. My goal is to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input. In this example, the first element can be split into two words: hello and cat because both of those words are in the dictionary.
You can create a Set from the dictionary (after splitting on a comma) and then test every single splitting point, checking if the two words obtained at each point exist in the Set.
function WordSplit([word, dictionary]) {
dictionary = new Set(dictionary.split(","));
for (let i = 0; i < word.length; i++) {
if (dictionary.has(word.slice(0, i)) && dictionary.has(word.slice(i))) {
console.log(word, 'can be split into', word.slice(0, i), 'and', word.slice(i));
return true;
}
}
return false;
}
console.log(WordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
The only way I can think of doing it is having a String Array of dictionary words. This obviously wouldn't be as comprehensive, and sort of laborious. You could check each word in strArr against each of your words in your String Array of dictionary words using a for loop, and if the word in strArr contains any dictionary word using the contains method, then you could split the word in strArr into two parts: part1 going from charAt 0 in str[i] until the CharSequence s, and part2 going from s to the end of str[i].
for(int i = 0; i < strArr.length; i++) {
for (int x = 0; x < words.length; x++) {
CharSequence s = words[x]
if(strArr[i].contains(s) {
String part1 = strArr[i].split(0,s);
String part2 = strArr[i].split(s);
}
System.out.println(part1 + "" + part2);
}
}
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);
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 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().
I am trying to get around the following but no success:
var string = 'erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ';
var x = string.split(' ');
for (i = 0; i <= x.length; i++) {
var element = x[i];
}
element now represents each word inside the array. I now need to reverse not the order of the words but the order of each letter for each word.
var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
// you can split, reverse, join " " first and then "" too
string.split("").reverse().join("").split(" ").reverse().join(" ")
Output: "There are a vast number of resources for learning more Javascript"
You can do it like this using Array.prototype.map and Array.prototype.reverse.
var result = string.split(' ').map(function (item) {
return item.split('').reverse().join('');
}).join(' ');
what's the map function doing there?
It traverses the array created by splitting the initial string and calls the function (item) we provided as argument for each elements. It then takes the return value of that function and push it in a new array. Finally it returns that new array, which in our example, contains the reversed words in order.
You can do the following:
let stringToReverse = "tpircsavaJ";
stringToReverse.split("").reverse().join("").split(" ").reverse().join(" ")
//let keyword allows you declare variables in the new ECMAScript(JavaScript)
You can do the following.
var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
arrayX=string.split(" ");
arrayX.sort().reverse();
var arrayXX='';
arrayX.forEach(function(item){
items=item.split('').sort().reverse();
arrayXX=arrayXX+items.join('');
});
document.getElementById('demo').innerHTML=arrayXX;
JavaScript split with regular expression:
Note: ([\s,.]) The capturing group matches whitespace, commas, and periods.
const string = "oT eb ro ton ot eb, taht si a noitseuq.";
function reverseHelper(str) {
return str.split(/([\s,.])/).
map((item) => {
return item.split``.reverse().join``;
}).join``;
}
console.log(reverseHelper(string));