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

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'))

Related

expand a string in JavaScript to display letter and how many times that letter appears

Write a function that accepts a string where letters are grouped together and returns new string with each letter followed by a count of the number of times it appears.
example : ('aeebbccd') should produce // 'a1e2b2c2d1'
function strExpand(str) {
let results = ""
for (let i = 0; i < str.length; i++) {
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length; j++) {
if (str.charAt(j) === charAt) {
count++;
}
}
results += count;
}
return results;
}
with the input 'aeebbccd' I am getting 'a1e2e2b2b2c2c2d1' instead of 'a1e2b2c2d1'
This function is adding a number after each character, which is the number of times this character appears anywhere in the string. You could instead do it like this to get the result you want.
function strExpand(str) {
let output = "";
// Iterate through each character of the string, appending
// to the output string each time
for (let i = 0; i < str.length; i++) {
let count = 1;
// If the next character is the same, increase the count
// and increment the index in the string
while (str[i + 1] == str[i]) {
count++;
i++;
}
// Add the character and the count to the output string
output += str[i] + count;
}
return output;
}
For sake of completeness,
how about a Regex?
const pattern = /(.)\1*/g; // put a char that exists in a capture group, then see if it repeats directly after
const s = 'aeebbccd';
var result = '';
for (match of s.match(pattern)) {
let this_group = match;
let this_len = match.length;
result = result + this_group[0] + this_len; // get only the first letter from the group
}
console.log(result); // a1e2b2c2d1
This would to the job. edit: hah i see im late :D, but still nice functional way to solve that.
/**
* #param string to count
* #return string $characterA$count. ex. abbccc -> a1b2c3
*/
function toCharacterCountString(str) {
return Array.from(new Set(str).values())
.map(char => {
return `${char}${(str.match(new RegExp(char, "g")) || []).length}`;
}).join('');
}
console.log(toCharacterCountString('abbccc')); // a1b2c3
console.log(toCharacterCountString('aeebbccd')); // a1e2b2c2d1

Write a function called strLetterCount which accepts a string and returns a new string with each letter and its count in the string

Write a function called strLetterCount which accepts a string and returns a new string with each character followed by the number of times it appears in the string. The characters should be returned in the same order as the string with each unique letter followed by the number of times it appears in the string.
My code so far is:
//write function format with argument
function strLetterCount (str){
//initialize var to hold results for charAt
let charAt = '';
let count = 0;
for(let i = 0; i < str.length; i++){
str.charAt(i);
results = str.charAt(i);
for (let j = 0; j < str.length ; j++){
if(str[i] === str){
count++
results = str.charAt(i) + count++
}
}
return results;
}
}
strLetterCount('taco'); //'t1a1c1o1'
//function should pass a string as argument
//loop through the string and if a new char is entered store that
//loop through string again and count num of new char
//returns a new string push charAt and numOfOcc
It should return the output of 't1a1c101' , however, I am only getting it to loop through the string once and return the first value of 't' but it's not counting the occurrences? I cant identify where to change my logic to hold the count of occurence?
I guess you try to achieve something like this.
Each letter will appear in output string with the same number of occurence as in the input string. I'm not sure that's what you want, but that's the thing the strLetterCount function intends to do.
function strLetterCount (str){
let results = ""
//initialize var to hold results for charAt
for(let i = 0; i < str.length; i++)
{
// Get current char and store it into the results
// We will add the count in a second loop
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length ; j++)
{
if(str.charAt(j) === charAt)
{
count++
}
}
results += count
}
return results;
}
Assuming that you don't need a count of each letter to be in the same position it started in, i.e. "started" can equal "s1t2a1r1e1d1" instead of "s1t2a1r1t2e1d1", than this should do the trick.
function strLetterCount (str){
// create an object to store each letter
const countObj = {}
// iterate over the string
for (let i = 0; i < str.length; i++) {
// if the letter isn't stored in the object, add it with a count of one
if (!countObj[str[i]]) {
countObj[str[i]] = 1;
} else {
// if the letter is already in the object, increment the count
countObj[str[i]]++;
}
}
// create a string to add the letter / count to
let outStr = "";
// iterate over the object to create the string
for (const letter in countObj) {
outStr += `${letter}${countObj[letter]}`;
}
// return the string
return outStr;
}
This would satisfy the requirements
function strLetterCount(str) {
// split the string to array
let strArr = str.split("");
// new array without duplicate letter
let strArrWithoutDuplicates = strArr.filter((value, idx, arr) => arr.indexOf(value) === idx);
let retString = "";
// loop through the "strArrWithoutDuplicates" array to find the number of times
// each elemet appears on the original array
strArrWithoutDuplicates.forEach(letter => {
retString += letter;
retString += strArr.filter((value) => (value === letter)).length;
});
return retString;
}
let a = strLetterCount('taco'); //'t1a1c1o1'
console.log(a)

Calculate spaces in string using Javascript function

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'));

Missing letters freecodecamp

Actually I found an answer a few minutes ago.
But I found something strange.
This is my answer for 'Missing letters' in freeCodeCamp challenges.
function fearNotLetter(str) {
var string;
for (i=0;i<str.length;i++) {
if(str.charCodeAt(i)+1 < str.charCodeAt(i+1)){
string = String.fromCharCode(str.charCodeAt(i)+1);
}
}
return string;
}
When I change < operator in if statement into != (not same), it doesn't work!
For me, it seems that != works exactly same as < operator does.
(Because 'not same' can mean something is bigger than the other.)
What is the difference between < and != in the code above?
Your code has a small defect that works when you use < but not !=.
If you see str.charCodeAt(i+1); this code is checking one spot past the end of the string on the last iteration and will return a NaN result.
If I provide the string "abce" it will check if f is < NaN. I believe NaN can't be compared to f's value so it doesn't go into the if statement. So it will keep the missing letter d that was found in the previous iterations which is stored in your string variable.
However, if you provide the !=, then with the same scenario it knows f != NaN and goes into the if statement. This then overwrite the actual missing letter and fails your FCC test case because it is replacing the missing d with f in your string variable.
To fix your code, simply change the for loop to end one iteration before the length of the string.
for (i = 0; i != str.length-1; i++) {
}
This is my method without using .charCodeAt() function :)
function fearNotLetter(str) {
var ind;
var final = [];
var alf =['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'];
str = str.split('');
ind = alf.splice(alf.indexOf(str[0]),alf.indexOf(str[str.length-1]));
for(var i=0;i<ind.length;i++){
if(str.indexOf(ind[i]) == -1){
final.push(ind[i]);
}
}
if(final.length != 0){
return final.join('');
}
return;
}
fearNotLetter("bcef");
My solution:
function fearNoLetter(str){
var j= str.charCodeAt(0);
for(var i=str.charCodeAt(0); i<str.charCodeAt(str.length-1); i++){
j = str.charCodeAt(i - str.charCodeAt(0));
if (i != j){
return String.fromCharCode(i);
}
}
}
My solution:
function fearNotLetter(str) {
let y = 0;
for (let i = str.charCodeAt(0); i < str.charCodeAt(str.length - 1); i++) {
if (str.charCodeAt(y) != i) {
return String.fromCharCode(i);
}
y++;
}
return;
}
console.log(fearNotLetter("ace"));
function fearNotLetter(str) {
let alpha = "abcdefghijklmnopqrstuvwxyz";
let alphabet = []
for(let j = 0; j< alpha.length; j++){
alphabet.push(alpha[j])
}
if (alphabet.length == str.length){
let result = undefined;
return result
}else{
const start =alphabet.indexOf(str[0])
let end = (str.length)-1
const stop = alphabet.indexOf(str[end])
const finish = alphabet.slice(start,stop)
let result = finish.filter(item => !finish.includes(item) || !str.includes(item))
result = String(result)
return result
}
return result
}
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"));

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;
}

Categories