Calculate spaces in string using Javascript function - javascript

I am working on a book and it is asking to create a function to find the spaces in a string. Not sure what I am doing wrong, but here is the code I have.
function calSpaces(str) {
var spaces = 0;
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
spaces ++;
}
return spaces - 1;
}
console.log(calSpaces("This is a test of spaces."));

You can do one trick like this:
var st = "Good morning people out there."
var result = st.split(' ');
var space_count = result.length-1;
console.log( space_count );

Your logic is working but you just miss one curly bracket in if condition.
function calSpaces(stringline)
{
var spaces = 0;
for(var i = 0; i < stringline.length; i++)
{
if (stringline[i] === ' ') {
spaces ++;
}
}
return spaces - 1;
}
Just add ending curly bracket and problem solved.
Also, returning space have total count - 1. is this intentionally done? if not then please remove - 1 from the count.
Here is the JSBIN link
happy coding.

A pretty simple solution is to use regex that will match spaces (and/or all whitespaces):
function countSpaces(str) {
return (str.match(/\s/g) || []).length;
}
function showCount() {
var str = document.getElementById('string').value;
document.getElementById('count').innerHTML = countSpaces(str);
}
<input type="text" id="string">
<button onclick="showCount()">Count Spaces</button>
<span id="count"></span>

Check your braces, one is missing
function calSpaces(str) {
var spaces = 0;
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
spaces ++;
}//end of IF
return spaces - 1;
}//end of FOR
//??? end of FUNCTION ???
console.log(calSpaces("This is a test of spaces."));
You were using return inside your for loop.
You only need to return spaces not spaces - 1
function calSpaces(str) {
var spaces = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
spaces++;
}
}
return spaces;//Outside of loop
}
console.log(calSpaces("This is a test of spaces."));

Here is how you can do it:
var my_string = "This is a test of spaces.";
var spaceCount = (my_string.split(" ").length - 1);
console.log(spaceCount)

A simpler solution is using regex to extract only the spaces from the string and count them:
function calSpaces(str) {
return str.replace(/[^\s]/g, '').length;
}
console.log(calSpaces("This is a test of spaces."));

Probably the simplest and shortest solution would be to use split() and get the length of an array:
var string = "This statement has lot of spaces and this spaces are never ending.";
var count = (string.split(' ').length - 1);
console.log(count)

There are other ways of doing that as other answers point out, but to answer your question on your exact problem: your parentheses are wrong. Try this snippet, now it works:
function calSpaces(str) {
var spaces = 0;
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
spaces++;
}
}
return spaces - 1;
}
console.log(calSpaces("This is a test of spaces."));

I would suggest an easier/faster approach using regex:
function calSpaces(str) {
count = (str.match(/\s/g) || []).length;
return count;
}
console.log(calSpaces('This is an example string'));

Related

Write a javascript program to Delete Even occurrences in a given string

I am finding problem in JavaScript code.
Write a JavaScript program to delete even occurrence in given string using function.
for example :
Input AAABBBCCC
OUTPUT: AABBCC (delet bold letters)
Input: AAAABBBBCCCC
OUTPUT: AABBCC
i am facing problem in function
A single regex should work:
console.log(remove('AAABBBCCC'))
console.log(remove('AAAABBBBCCCC'))
function remove(str) {
return str.replace(/(.)\1/g, '$1')
}
(.)\1 matches duplicated characters
Solution with a for loop:
function stripEven(str) {
let res = '';
let counter = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] !== str[i-1]) counter = 0;
if (counter % 2 === 0) res += str[i];
counter++;
}
return res;
}
console.log(stripEven('AAABBBCCC'))
console.log(stripEven('AAAABBBBCCCC'))
console.log(stripEven('AAABBCCC'))

Trying to create a palindrome function that accounts for spaces

Okay so palindrome is a word that is the same spelled backwards. What if we want to take a phrase that is also the same backwards? So kook is one. race car is another one.
So I made one that doesn't account for spaces.
function isPal(string){
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
This one works fine for words.
Now I'm thinking, push the string into an array, and split up each character into it's own string, then remove any spaces, and then run if (string.charAt(i) != string.charAt(string.length - i - 1)). So here's what I wrote but failed at..
function isPalindrome(string){
var arr = [];
arr.push(string.split(''));
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
if I return arr, it still gives me the string with the space in it. How do I accomplish this? Thanks!
EDIT: Used the solution but still getting false on 'race car'
Here's what I got:
function isPalindrome(string){
var arr = string.split('');
for (i = 0; i < arr.length; i++){
if (arr[i] === ' '){
arr.splice(i, 1);
} else if (arr[i] != arr[arr.length - i - 1]){
return false;
}
}
return true;
}
where's my error?
Your problem is in the following line:
arr.push(string.split(''));
string.split('') returns an array. So, arr is actually an array with one entry it in (another array that contains your characters). Replace:
var arr = [];
arr.push(string.split(''));
with
var arr = string.split('');
and it should work as expected
Just check check the string without spaces:
function isPal(string){
string = string.split(" ").join(""); // remove all spaces
var l = string.length;
for (var i = 0; i < (l/2); ++i) {
if (string.charAt(i) != string.charAt(l - i - 1)){
return false;
}
}
return true;
}
isPal("a man a plan a canal panama"); // true
It seems much easier to just split into an array, reverse and join again to check if a word is a palindrome. If you want to ignore spaces, just remove all instances of spaces:
let word = 'race car';
let isPalindrome = (word) => {
let nospaces = word.replace(/\s/g, '');
return [...nospaces].reverse().join('') === nospaces;
}
Or non-es6:
var word = 'race car';
var isPalindrome = function(word) {
var nospaces = word.replace(/\s/g, '');
return nospaces.split('').reverse().join('') === nospaces;
}

Javascript: in a string, replace the capital letter and all letters following it

I have a bunch of strings, dateTable, lastName, redColor and I want to remove the capitalized letter and all letters after that, for example, remove Table, Name, and Color and leaving only date, last, and red. Any help is appreciated!
Can be done easily using .replace():
"dateTable".replace(/[A-Z].*/, "")
Iterate through the letters and match them to a regex. Then use the sub string to get the string from start to index of the first upper case letter.
var inputString = "What have YOU tried?";
var positions = [];
for(var i=0; i<inputString.length; i++){
if(inputString[i].match(/[A-Z]/) != null){
positions.push(i);
break;
}
}
alert(positions);
var res = str.substring(1, postions[0]);
res should be the intended string
Here is a method that will alert what you wanted - you can continue from there
Check it:
function checkWord(word) {
var foundFirst = false;
var lengthToChop = 0;
for (var i in word) {
foundFirst = /^[A-Z]/.test( word[i])
if (foundFirst){
lengthToChop = i;
break;
}
}
alert(word.substring(0, lengthToChop));
}
Simple fast non-regex loop that breaks at the first capital letter.
function strip(str) {
var i = -1, out = [], len = str.length;
while (++i < len) {
if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) break;
out.push(str[i]);
}
return out.join('');
}
DEMO
try this code. No regular expressions... it should work and is pretty simple. Here is the fiddle... https://fiddle.jshell.net/4ku3srjw/2/
Just replace the string for the variable word and you'll see it works for what you want
var word = "lastName";
for (var i = 0; i < word.length; i++) {
if (word[i] === word[i].toUpperCase()) {
var choppedWord = word.substr(0, i)
}
}
alert(choppedWord);
Hope it helps

Check if string character matches array value

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.

Dividing words from text starting with a certain character

I want to test each word from a text if it starts with the character # if it does, i will put the word in variable 'response' if not, i will continue searching.
I tried something like :
var found = false;
for (i = 0; i < text.length; i++) {
if (found = /^#...$/.test(text[i])) {
found = true;
}
if (found== true){
//other stuff
}
}
could you help me with this one ?
You can use split on space, and then use substring to find the first letter. Then compare it.
Demo
var arr= text.split(' ');
for (i = 0; i < arr.length; i++) {
if (arr[i].substring(0,1) == '#') {
console.log('found!: ' + arr[i]);
break;
}
}
You probably want something like:
var found = false, response;
for (i = 0; i < text.length; i++) {
if (/^#.*$/.test(text[i])) {
found = true;
response = text[i];
break;
}
}
That matches everything that starts with a #. If you just want to match non-space characters, use the RegEx /^#(\S)*$/

Categories