so I need to be able to enter a string and have it reversed. I must have one library JS file and one regular JS file. Here is my library JS file:
function reverseString(string) {
var reversedString= "";
for(var i = string.length -; i >=; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
and here is my regular one
var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")
I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. What am I missing?
There're a lot of syntax issues. Here's a working code:
function reverseString(string) {
var reversedString = "";
// This loop had a lot of basic syntax issues and also
// "i" was starting from the length value, while a string
// is a character array and array indexes start from 0 instead of 1
for (var i = string.length - 1; i >= 0; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
var stringEntered = prompt("Enter a string:");
var newString = reverseString(stringEntered);
// Here I found a mess of "/" characters
// I've changed the horrible document.write with alert so you can check the result without opening the debugger...
alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Here is a concise method of reversing a string:
function reverseString(string) {
return string.split('').reverse().join('');
}
var str = prompt("Enter a string", "a racecar dad");
alert(reverseString(str));
Turn it into an array, reverse the array, turn it back into a string.
Edit: Sorry, didn't see #SidneyLiebrand's comment telling you to do the same.
Related
This project is in javascript. I need to make sure the output retains spaces found in the string that is inputted into the function. The test I am trying to pass is calling the function for the term "hello world" with a shift of 13 letters. From this code, the result is "uryybjbeyq" and "uryyb jbeyq" is expected. I have identified I need an if statement which I have included already, but not sure what command I should include before the continue keyword that will insert the space needed. I am a beginner and this is only my 3rd project so any assistance would be appreciated. Please find the corresponding code below.
function caesarCypher(string, num){
// line below is the encrypted string we will return from the function
const letters = 'abcdefghijklmnopqrstuvwxyz';
let encryptStr = ""
// loop through every character in the inputted string
for(let i = 0; i < string.length; i++){
// line below will look up index of char in alphabet
let char = string[i];
/* if statement below is attempting to identify the space in the original string and then add a command that will add a space to the encrypted string then continue to work through the rest of the input */
if (char === " ") {
//need something to put on this line to insert space;
continue;
}
let index = letters.indexOf(char);
// index + num below will give us the letter 7 spots over
let newIndex = index + num;
// if statement below makes the function loop back around
if (newIndex > 26) {
newIndex = newIndex - 26;
}
let newChar = letters[newIndex];
encryptStr += newChar;
}
return encryptStr;
}
/* invoke the function with these parameters to pass the test-- expected result is 'uryyb jbeyq'*/
caesarCypher("hello world", 13)
You can add the white space like this:
encryptStr += " ";
I tried your code and I ran into an error... All letters were the same. Here is how I did it:
function caesarCypher(string, num){
let encryptStr = "";
for(let i = 0; i < string.length; i++){
let char = string[i];
if (char === " ") {
encryptStr += " "; //This adds a white space.
continue;
}
// If you want to keep the case of a letter, skip the
// "toLowerCase()" and extend the condition below.
let asciiCode = string.toLowerCase().charCodeAt(i) + num;
if(asciiCode > 122) {
asciiCode -= 26;
}
encryptStr += String.fromCharCode(asciiCode);
}
return encryptStr;
}
I apologize if this question has been answered somewhere - please point me in the right direction if so. I have read through a bunch of solutions and have not yet cracked it!
Sooo...basically, I need to:
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
This is my code so far:
function pigIt(str) {
var newStr = str.split(" ");
var changed = newStr.map(function(input) {
return input.substring(1) + input.charAt(0) + "ay";
});
changed = changed.join(" ");
return changed;
}
console.log(pigIt('Pig latin is cool'));
As you can see, the code will work for any input that doesn't include punctuation. Great. Now I need to maybe add a Regex somewhere to exclude punctuation but I don't know where to put it! Please help!!
You could split by the word boundary /(\W+)/ while capturing separator. Transform words only. And then join back.
function pigIt(str) {
var newStr = str.split(/(\W+)/); // ['Pig', ' ', 'latin', ',- ',..]
var changed = newStr.map(function(input) {
if (!/\w/.test(input)) return input // keep non word elements as is
return input.substring(1) + input.charAt(0) + "ay";
});
return changed.join("");
}
console.log(pigIt('Pig latin,- is cool!'));
I think because you are going to want to put the punctuation back in the same place after processing, then you will probably be better of doing it all manually.
Loop the input 1 char at a time and build a 'word buffer', every time you hit a non-letter character then process the word buffer and append the non-letter character too.
function pigIt(str) {
var process = function(s) {
if (s.length < 2) {
return s;
}
return s.substring(1) + s.charAt(0) + "ay";
};
var result = '';
var buffer = '';
for (var i = 0; i < str.length; i++) {
var c = str[i];
if (c.match(/[a-zA-Z]/i)) {
buffer += c;
} else {
if (buffer.length) {
result += process(buffer);
buffer = '';
}
result += c;
}
}
result += process(buffer);
buffer = '';
return result;
}
var output = pigIt('Pig latin is cool.');
console.log(output);
This question already has answers here:
How to remove spaces from a string using JavaScript?
(15 answers)
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 6 years ago.
I created a function to delete the spaces out of a string and return the strings length with out spaces, however the function is deleting more then just the spaces. Also is there a better way of accomplishing this, assuming this function can be fixed.
let string="This string is going to lose characters";
function charLength(str){
let strArray=str.split("");
let output="";
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1);
}
else{
output+=strArray[i];
}
}
return output.length // + " " output, if I were to add this you would see its deleting characters
}
charLength(string);//returns "27 Thistringsoingooseharacters", not "33 Thisstringisgoingtolosecharacters"
When you remove a character from the string you'll have to go back one step (i--) st the loop won't skip a character (for(... ; i++)). Like this:
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--; // ge back one step if we remove one character.
}
Snippet:
let string = "This string is not going to lose characters";
function charLength(str) {
let strArray = str.split("");
let output = "";
for (let i = 0; i < strArray.length; i++) {
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--;
} else {
output += strArray[i];
}
}
return output;
}
console.log(charLength(string));
If you want to count characters that are not spaces:
Then just make a counter that will count the characters that are not spaces like this:
let string = "This string is not going to lose characters";
function charLength(str) {
let counter = 0; // the counter
for (let i = 0; i < str.length; i++) { // for each character in the string
if(str.charAt(i) !== ' ') // if the character is not a space
counter++; // increment the counter
}
return counter;
}
console.log(charLength(string));
The reason why characters get lost, is because the list is modified inside the loop.
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1); // Items are removed here
...
When you remove an character i, the next character will take its place.
You could maybe use the replace function instead like this:
string.replace(/ /gi, "").length
Use regex.
var str = 'This string is going to lose characters';
// The substituted value will be contained in the result variable
const result = str.replace(/\s/g, '');
console.log('Substitution result: ', result.length);
You don't need a regex: str.replace(" ","") is already doing that.
Instead of this line here:
strArray.splice(strArray[i],1);
Try using this:
strArray.splice(strArray[i],0);
Just replaces the 1 with 0
This is much simpler than you are doing. You can just use the .replace() string method which can take a string literal to replace or a regular expression.
function charLength(str){
// Create a new string that is the same as the passed in one, but with the spaces stripped out
// The syntax / / denotes a regular expresion (regEx) object
// The s+ denotes to look for one or more spaces in a row
// The g denotes a global search and replace througout the string
var newStr = str.replace(/\s+/g, "");
console.log("\"" + str + "\" has: " + str.length + " characters.");
console.log("\"" + newStr + "\" has: " + newStr.length + " characters.");
}
charLength("This string is going to lose characters");
You could use eiter a regular expression for filtering space
var string = "This string is going to lose characters",
result = [...string].filter(RegExp.prototype.test.bind(RegExp('[^ ]'))).join('');
console.log(result);
console.log(result.length);
Or just test for space.
var string = "This string is going to lose characters",
result = [...string].filter(a => a !== ' ').join('');
console.log(result);
console.log(result.length);
Please help me. I'm doing exercise and I don't understand what I'm doing wrong if all conditions execute. The task consists in returning the provided string with only the first letter of each word capitalized. My code performs this condition, but It doesn't get me ahead.
function titleCase(str) {
var text = str.toLowerCase();
var arr = text.split(" ");
var txt = " ";
var i;
for(i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1) + " " ;
}
return txt;
}
titleCase("sHoRt AnD sToUt");
You are adding extra whitespace (var txt = " " should be var text = ''), try this instead:
function titleCase(str) {
var text = str.toLowerCase();
// split on spaces, map over array and return capitalized word and join on space
return text.split(' ').map((word) => {
return word[0].toUpperCase() + word.slice(1);
}).join(' ');
}
alert(titleCase("sHoRt AnD sToUt"));
If your goal is to return the string back with the first letters capitalized, I can see one problem in your output. You should be returning
"Short And Stout"
but instead you return
" Short And Stout "
with a space before and after your string. You can fix this by initializing txt to an empty string rather than a space, and then either trimming the last space off at the end after your loop, or by only adding the space if you aren't on the last element of arr. That is:
var txt = "";
for(var i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1);
if (i != arr.length - 1) txt += " ";
}
You can use regular expression instead.
function titleCase(txt){
return txt.toLowerCase().replace(/\b\w/g, function(m){return m.toUpperCase();});
}
console.log(titleCase("sHoRt AnD sToUt"));//"Short And Stout"
Some explanation.
// regular expression (RegEx), g for global (else first only)
\b word boundary
\w any word symbol a-z (plus _)
m (function parameter) is match in the string
Having trouble coming up with code doing this.
So for example here is my string.
var str = "Hello how are you today?";
How would I manipulate this string to return the position of the first letter of each word using a loop?
this will give you the result with less complicated code and a single loop
function foo(str) {
var pos = [];
var words = str.split(' ');
pos.push(1);
var prevWordPos;
for (var i = 1; i < words.length; i++) {
prevWordPos = pos[i - 1] + words[i - 1].length;
pos.push((str.indexOf(words[i], prevWordPos) + 1));
}
return pos;
}
You should search for a question before asking it in case it's already been asked and answered.
Get first letter of each word in a string, in Javascript
You can use a regexp replace passing a function instead of a replacement string, this will call the function for each match:
str.replace(/[^ ]+/g, function(match, pos) {
console.log("Word " + match + " starts at position " + pos);
});
The regexp meaning is:
[^ ]: anything excluding space
+: one or more times
"g" option: not only first match, but each of them
in other words the function will be called with sequences of non-spaces. Of course you can define what you consider a "word" differently.
Here is a Solution with two Loops, i hope that is close enough ;)
var starts = [];
var str = "How are you doing today?";
//var count = 0;
var orgStr = str;
while (str.indexOf(" ") > 0) {
if (starts.length > 0) {
starts.push(starts[starts.length - 1] + str.indexOf(" ") +1);
} else {
starts.push(1);
starts.push(str.indexOf(" ") +2);
//alert(str);
}
str = str.substring(str.indexOf(" ") + 1);
}
for (var i = 0; i < starts.length; i++) {
alert(starts[i] + ": " + orgStr.substring(starts[i]-1,starts[i]))
}
Easiest would be to search a regular expression \b\w and collect match.start() match.index for each match. Loop while there's matches.
EDIT: wrong language. lol.