Reversing a Sentence without reversing Characters in JavaScript - javascript

how do i reverse a sentence like "Hello World" to "World Hello" Not dlroW oleo
Been search for an example on this forum the whole day
function jump(str){
var holder ="";
var len = str.length-1;
for(var i =len; i >= 0; i--){
holder += str[i] ;
}
return holder.trim();
}
console.log(jump("Just do it!"))

In JavaScript there is a really easy way to do this:
var str = "Hello World";
str = str.split(" ").reverse().join(" ");
console.log(str); // => "World Hello"
Basically, you split the string into an array using a space character as a delimiter so we can get an array of each word, then reverse that array and join them back into a string with the spaces we removed earlier.

As you have not mentioned which language you are using, I will give you just steps
Steps:
Split by space, and store in an array or list
Reverse the order
Print by looping through the list

Related

Why does toLowerCase() does not work with replace()?

Given Below is a simple function to capitalize the first words in a sentence
Eg: INPUT: 'JavaSCRipt is The BEST'
OUTPUT: 'JavaScript Is The Best'
const firstupper = function(str){
const arr = str.split(' ');
const newArr = [];
for(let item of arr){
item = item.toLowerCase();
newArr.push(item.replace(item[0], item[0].toUpperCase()));
}
const newstr = newArr.join(' ');
console.log(newstr);
}
firstupper('javaSCript is THE besT');
P.S -- This code works fine
Why can't I make to lower case and then replace the first letter in upper case in single line
like : newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));
When I write the code using this it is changing the first word to lower if it is in upper case vice versa
Eg: INPUT -> 'JAvaScript is The best'
OUTPUT - > 'javascript Is the Best'
Because that changes the logic. In this version, all reads of item in the .push() operation are lower-cased:
item = item.toLowerCase();
newArr.push(item.replace(item[0], item[0].toUpperCase()));
But in this version, only the first use of item is lower-cased:
newArr.push(item.toLowerCase().replace(item[0], item[0].toUpperCase()));
The references to item[0] both still use whatever the original casing was. To make it the same logic you'd need to repeat the case change there as well:
newArr.push(item.toLowerCase().replace(item.toLowerCase()[0], item.toLowerCase()[0].toUpperCase()));
Which clearly is too cluttered and unnecessarily repeats the operation. So the original working version is preferred.
This could help
const str = 'JavaSCRipt is The BEST';
//split the above string into an array of strings
//whenever a blank space is encountered
const arr = str.split(" ");
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].toLowerCase();
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
//Join all the elements of the array back into a string
//using a blankspace as a separator
const str2 = arr.join(" ");
console.log(str2);
//Outptut: Javascript Is The Best

How to console log a word in a string?

I'm wondering how to console.log a word from a string based on the index.
let word = "Hello world";
console.log(word[0]) //log from index 0 to 4
How to log from index 0 to 4, because now i only know how to log a single letter.
Like this:
let word = "Hello world";
let wordArray = word.split(" ");
console.log(wordArray[0])
Split your string by your separator in your case space:
console.log(word.split(" ")[0]);
You can either use split to get an array of the words and then use to index of the word position
let sentence = "Hello world";
console.log(sentence.split(" ")[0]);
or if you know what word you are looking for you
can use indexOf together with the word length to slice it.
let sentence = "Hello world";
console.log(sentence.slice(sentence.indexOf("Hello"), "Hello".length));
Its ez mate,
first create function
function clwobo(str){
let a = str.split(" ")//Create an "a" variable to split "str" into an array
return a[0]//This function will return the first word of the string, 1 will be 2 and so on
}
How to use this function?
Well
clwobo("Hello world")
In console it will show
-- Console --
Hello
Try it first, then mark if its work.

Write a method that takes in a sentence string and returns a new sentence representing its Aba translation

Beginner Coder and I'm confused if my include method is wrong. Maybe I should create an array and push the characters in? Am I on the right track?
Aba is a German children's game where secret messages are exchanged. In Aba, after every vowel we add "b" and add that same vowel. Write a method that takes in a sentence string and returns a new sentence representing its Aba translation. Capitalized words of the original sentence should be properly capitalized in the new sentence.
function abaTranslate(sentence) {
var words = sentence.split(" ");
const vowels = 'AEIOUaeiou';
var newStr = "";
var char = words[i];
for (var i = 0; i < sentence.length; i++) {
if (words.includes(vowels)) {
newStr += (words + "b")
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
You don't need to split your sentence into individual words, as you're not interested in looking at the words, but rather the individual characters in the sentence. With this in mind, you can use the current loop that you have, and for each i grab the current character from the input sentence at index i.
If the current character is a vowel (ie: if it is included in the vowels string), then you know the current character is a vowel, and so, you can add the current character separated by a "b" to your output string. Otherwise, it if its not a vowel, you can just add the current character to the output string.
See example below:
function abaTranslate(sentence) {
const vowels = 'AEIOUaeiou';
var newStr = "";
for (var i = 0; i < sentence.length; i++) {
var currentCharacter = sentence[i];
if (vowels.includes(currentCharacter)) { // the current character is a vowel
newStr += currentCharacter + "b" + currentCharacter;
} else {
newStr += currentCharacter; // just add the character if it is not a vowel
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
If you want to use JS methods to help you achieve this, you could use .replace() with a regular expression. Although, it's probably better to try and understand the above code before diving into regular expressions:
const abaTranslate = sentence => sentence.replace(/[aeiou]/ig, "$&b$&");
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"

How can I split commas and periods from words inside of string using split?

I am trying to change specific word in a string with something else. For example, I want to change 'John' in let name = 'Hi, my name is John.'; to 'Jack'.
I know how to split a string by words or characters. I also know how to remove commas, periods, and other symbols in a string. However, if I split the given string with a separator (" "), I will have 'John.' which I do not want. (I know I can switch 'John.' with 'Jack.' but assume that I have an key and value pairs in an object and I am using the values which are names {Father: Jack, Mother: Susan, ...}
I don't know how to separate a string word by word including commas and periods.
For example, if I was given an input which is a string:
'Hi, my name is John.'
I want to split the input as below:
['Hi', ',', 'my', 'name', 'is', 'John', '.']
Does anyone know how to do it?
Below is the challenge I am working on.
Create a function censor that accepts no arguments. censor will return a function that will accept either two strings, or one string. When two strings are given, the returned function will hold onto the two strings as a pair, for future use. When one string is given, the returned function will return the same string, except all instances of a first string (of a saved pair) will be replaced with the second string (of a saved pair).
//Your code here
const changeScene = censor();
changeScene('dogs', 'cats');
changeScene('quick', 'slow');
console.log(changeScene('The quick, brown fox jumps over the lazy dogs.')); // should log: 'The slow, brown fox jumps over the lazy cats.'
I think your real question is "How do I replace a substring with another string?"
Checkout the replace method:
let inputString = "Hi, my name is John.";
let switch1 = ["John", "Jack"];
let switched = inputString.replace(switch1[0], switch1[1]);
console.log(switched); // Hi, my name is Jack.
UPDATE: If you want to get ALL occurrences (g), be case insensitive (i), and use boundaries so that it isn't a word within another word (\\b), you can use RegExp:
let inputString = "I'm John, or johnny, but I prefer john.";
let switch1 = ["John", "Jack"];
let re = new RegExp(`\\b${switch1[0]}\\b`, 'gi');
console.log(inputString.replace(re, switch1[1])); // I'm Jack, or johnny, but I prefer Jack.
You can Try This ...
var string = 'Hi, my name is John.';
//var arr = string.split(/,|\.| /);
var arr = string.split(/([,.\s])/);
console.log(arr);
Using 'Hi, my name is John.'.split(/[,. ]/); will do the job. It will split commas and periods and spaces.
Edit: For those who want to keep the comma and period, here is my wildly inefficient method.
var str = 'Hi, my name is John.'
str = str.replace('.', 'period');
str = str.replace(',', 'comma');
str = str.split(/[,. ]/);
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf('period') > -1) {
str[i] = str[i].replace('period', '');
str.splice(i+1, 0, ".");
} else if (str[i].indexOf('comma') > -1) {
str[i] = str[i].replace('comma', '');
str.splice(i+1, 0, ",");
}
}
console.log(str);

How to get abc from "abc def"?

"abc def"
"abcd efgh"
If I have a large string with a space that separates two substrings of varying length, what's the best way to extract each of the substrings from the larger string?
Because this is a string rather than an array, array syntax s[0] will only retrieve the first letter of the string ('a'), rather than the first substring.
Use the split method of the String object:
"abc def".split(' ')[0] // Returns "abc"
Works like this:
"string".split('separator') // Returns array
var arr = "abc def".split(" ");
document.write(arr[0]);
should work
Both above Answer's are right I am just putting it so that user can do some operation with every token. All you need to add a loop for that.
function splitStr(str){
var arr = str.split(" ");
for(i=0 ;i < arr.length ; i++){
//You will get a token here
// var token = arr[i];
// Do some thing with this token
}
}
One can return the array for any other operation in other function as
function splitStr(str){
var arr = str.split(" ");
return arr;
}

Categories

Resources