I have come across a question about calculating sentences using a form in HTML, but I wanted to work out the function first to see if it would work. Here is my function that I have not been able to get it working in jsfiddle (https://jsfiddle.net/jdloomis/fxt81ynu/2/):
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
}
console.log(calSentences("This is a sentence. My second sentence."));
I have been able to figure out most of the functions and what they do in my book except this one and a word count without using .split, I will post that one in another post if I cannot figure it out.
You were so close with your attempt! All you forgot to do is return the number of sentences with return numSentences:
var numSentences = 0;
function calSentences(longString) {
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));
Hope this helps! :)
Your code is correct, but you are not returning anything from your function.
Also, keep var numSentences local to your function, so that it's reset to 0 each time you run your function. Otherwise, you are adding on to the previous calculation each time you run the function.
function calSentences(longString) {
var numSentences = 0;
var length = longString.length;
var sentence = '';
for (var i = 0; i < length; i++) {
sentence += longString[i];
if (longString[i] == '.') {
numSentences++;
sentence = '';
}
}
return numSentences;
}
console.log(calSentences("This is a sentence. My second sentence."));
Related
I'm trying to make a program where if you write in a word, let's say "Hello". And then you press the print button the outcome would be this:
"H"
"He"
"Hel"
"Hell"
"Hello".
Should i use a loop for this? My code so far is this:
function printit()
{
var temptext = document.getElementById("mytext").value;
temptext = temptext.slice(1,2);
document.getElementById("translated").innerHTML=temptext;
}
Anyone got any suggestions on how to solve this?
Here's how this would work with a loop.
Loop over the characters
Use the loop counter (i) to progressively slice the required chunk off your text.
Make sure you slice(0, i + 1), so you don't slice(0, 0) on the 1st iteration
function print() {
var text = document.querySelector("#text").value
for(var i = 0; i < text.length; i++) {
console.log(text.slice(0, i + 1))
}
}
<input id="text" value="Hello"/>
<button onclick="print()">Print</button>
You can use .map() with a scoped variable, to return an array of the words you need
function toSplicedWordArray(what) {
var before='';
return what.split('').map(function(item) {before+=item;return before;});
}
console.log(toSplicedWordArray('hello'));
try this:
let word = 'Good';
for (let i = 1; i <= word.length; i++) {
console.log(word.substring(0, i));
}
function printinit() {
var tempText = document.getElementById("mytext").value;
var slicedText = "";
for (var i = 0; i < tempText.length; i++) {
slicedText = tempText.slice(0, i) + " ";
}
document.getElementById("translated").innerHTML = temptext;
}
I have this code here:
var regex = /smell(y)?|poo/ig; //Banned Words
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
function profanity() {
var array = [];
$('font').each( function() {
var string = $(this).html();
var pos = countInArray(array, $(this));
array.push($(this));
var updatedString = string.replace( regex, function(s) {
var i = 0;
var asterisks = "<span title='Blocked Word/Phrase!\nBlocked By Profanity Filter'>";
while (i < s.length) {
asterisks += "*";
i++;
}
asterisks = asterisks.concat("</span>");
$('font').html(asterisks)[pos];
});
});
}
The code basically scans through each font element for the banned words, however I cannot get it to replace the text for that element only all elements or none at all, I have tried to make an array which will add the value then scan for how many times it is there to try and get it but I am still having problems, can anyone help. I have searched everywhere, but I cannot find or replicate my problem anywhere. Can anyone help me, any help would be appreciated. Thanks!
I'm having a little trouble with a small challenge. I'm trying to check to see if a string's character is found in an array and if so, stop the loop, log the value, and start over with a new string character. Can anyone elp
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
// code goes here
var myString = "";
for(var i = 0; i <= myString.length; i++) {
for(var o = 0; o < 25; o++){
var getChar = myString += str.charAt(i)
if (getChar == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test");`
function LetterChanges(str) {
// code goes here
var regex=/[abcdefghijklmnopqrstuvwxyz]/;
// simply you can give as below
regex = /[a-z]/;
//if you want to match Cap A-Z too make the regex to ignore case as below
// regex = /[a-z]/i;
var myString = "";
for (var i = 0; i < str.length; i++) {
var char = str[i];
if (regex.test(char)) {
myString += char;
console.log(myString)
}
}
console.log(myString);
}
// keep this function call here
LetterChanges("Test");
If you're just starting out, take a look at how to use debugger and breakpoints. They'll help you figure out what your code is doing.
Try looping over alphabet.length instead of 25
Creating var getChar seems unnecessary. Try just doing if(str.chartAt(i) == alphabet[o])
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
for(var i = 0; i <= str.length; i++) {
for(var o = 0; o < 25; o++){
if (str.charAt(i) == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test"); </script>
note that , letter 'T' will not match in array. so only 'e' , 's' , 't' will be alert.
I have been stumped on this problem for a few hours now and am making no progress. I feel like this should be simple. I am trying to Remove duplicate characters in a String without using methods such as Filter or a Reg ex.
Here is my current code:
var duplicate = function(string) {
var newString = string.split("");
var finalArrayWithNoDuplicates = []
for (var i = 0; i < newString.length; i++){
for (var=0; j < newString.length; i++){
while(newString[i])
if (newString[i] !== newString[j]){
}
}
}
return finalArrayWithNoDuplicates.join("");
};
I am able to filter one letter at a time but as I progress down the chain in the while statement I am adding letters that were filtered out originally.
All of the algorithm tutorials for this algorithm are in Java that I have been finding. Is there a way to do this with only using a a for and while loops?
There are several things wrong with the proposed code:
It has serious errors (the inner loop is written all wrong)
You don't need to involve arrays at all, strings will do just fine
The "if char !== other char" check will never provide enough information to act on
Here's an alternative version using for loops and the same basic idea:
function deduplicate(str) {
var result = "";
for (var i = 0; i < str.length; ++i) {
var found = false;
for (var j = 0; j < i; ++j) {
if (str[i] == str[j]) {
found = true;
break;
}
}
if (!found) result += str[i];
}
return result;
}
Each character str[i] in the input string is compared to all characters str[j] that precede it (there is no point in comparing to characters that follow it because we are going to process those when their turn comes up anyway). If the character is not equal to any of those that precede it then we know it's the first of its kind to appear and include it in the result.
Note that this algorithm has O(n²) performance, which is very poor compared to other possible approaches. Its main selling point is that it is straightforward and that everything happens "in front of your eyes".
Here is a slightly modified version of your function that uses an object to keep track of which letters have already been encountered:
var duplicate = function(string) {
var finalArrayWithNoDuplicates = [];
var seen = {};
for (var i = 0; i < string.length; i++) {
if (!seen[string[i]]) {
finalArrayWithNoDuplicates.push(string[i]);
seen[string[i]] = 1;
}
}
return finalArrayWithNoDuplicates.join("");
};
No need for two nested for-loops
No need for "while" loop as well
in the following line of code there are two errors: for (var=0; j < newString.length; i++){ first one is var=0 (compilation error) and second is theat you increment i instead of j
It can be done by adding only unique elements (that don't appear twice) to finalArrayWithNoDuplicates
as follows:
var duplicate = function(newString) {
var finalArrayWithNoDuplicates = []
var x = 0;
for (var i = 0; i < newString.length; i++){
// if the char appears in another index
// or if it's already in the result - don't add it
if (newString.lastIndexOf(newString[i]) !== i || finalArrayWithNoDuplicates.indexOf(newString[i]) > -1){
continue;
}
else{
finalArrayWithNoDuplicates[x++] = newString[i];
}
}
return finalArrayWithNoDuplicates.join("");
};
var arr = [1,2,3,4,5,4,5,6,7];
alert(duplicate(arr));
OUTPUT:
1234567
I have written this function (which is not working) which is supposed to count the letters in a global variable (paraText), and then insert it to count. How do I solve this?
This is a school project so I have to follow sertain rules. I have tried almost all answers but I can't get it to work :( maybe if you look at all the code you can see what I'm doing wrong.
"use strict";
var paraText = "";
var antalParagrafer = 0;
function addLetter(c) {
if(!paraText) {
addParagraph();
}
else { //add c to saved textnode
var tNod = document.createTextNode(c);
paraText.appendChild(tNod);
}
}
//function is called when enter is pressed
function addParagraph() {
/*create a new paragraph with related textnode
textnode is saved to the global textnodevariable
add paragraph to the div with id "output"
you also need to mark the paragraph with the class even/odd
depending on the class of the previous paragraph*/
var div = document.getElementById("output");
var nyParagraf = document.createElement("p");
div.appendChild(nyParagraf);
antalParagrafer += 1;
nyParagraf.className = (antalParagrafer % 2 === 0 ? 'even' : 'odd');
paraText = nyParagraf;
}
//function is called when count letters is pressed
function countLetters() {
var count=0;
for(var i = 0; i < paraText.length; i++) {
var c = paraText.charAt(i);
if (c >= 'a' && c <= 'z') count++;
}
return count;
}
I'd just strip out the non-letters and then use the length of what's left:
var count = paraText.replace(/[^a-zA-Z]/g, '').length;
Your function works otherwise fine (although it's perhaps not as elegant as it could be), but count = count ++ is wrong; either use
count++;
or
count = count + 1;
The statement count = count++ doesn't increase the counter, because the value of count++ is what's in the variable before it is increased, so you increse the variable, then assign back the value that was before.
Using a simple comparison gives better performance than using a regular expression for each character in the string:
function countLetters() {
var count=0;
for(var i = 0; i < paraText.length; i++) {
var c = paraText.charAt(i);
if (c >= 'a' && c <= 'z') count++;
}
return count;
}