capitalize the first letter of each word in a sentence - javascript

hey guy can anybody help me to fix my code so that it does the task shown in the text,
function tad(strg) {
var char = strg.split('-')
for (var i = 1; i < char.length; i++) {
return char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
}
camelize("background-color") == 'backgroundColor'
camelize("list-style-image") == 'listStyleImage'

Assuming you want to replace all word combinations that have a hyphen in it to a camel cased word. You can use a regex with String.replace with a callback function that capitalizes all words after the hyphen.
function camelize (strg) {
return strg.replace(/-(\w)/g, function (match) {
return match[1].toUpperCase();
});
}
camelize("background-color");
// backgroundColor
camelize("z-index");
// zIndex
camelize("list-style-image");
// listStyleImage
JSFIDDLE

Change your function like bellow
function tad(strg) {
var char = strg.split('-')
for (var i = 1; i < char.length; i++) {
char[i] = char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
return char.join('');
}

You are returning before the loop completes its iterations. The best thing here would be to use Array.prototype.reduce like this
function tad(strg) {
return strg.split('-').reduce(function(result, currentStr) {
return result + currentStr.charAt(0).toUpperCase() + currentStr.slice(1);
}, "");
}
console.log(tad("background-color") === "backgroundColor");
# true
console.log(tad("list-style-image") === "listStyleImage");
# true

First of all, you should concatenate results in some variable, instead of returning in loop.
Secondly fo not forget to add first element of array, since your loop is starting from 1.
function camelize(strg) {
var char = strg.split('-'), result = char[0]
for (var i = 1; i < char.length; i++) {
result += char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
return result
}
alert(camelize("background-color"));
alert(camelize("list-style-image"));
Here is fiddle:
http://jsfiddle.net/C78T3/

You return from the whole function in the first iteration of that loop. Instead, you want to do that for every part, and the join the parts together:
function camelize(string) {
return string.split('-').map(function(part, i) {
return i ? part.charAt(0).toUpperCase() + part.slice(1) : part;
}).join("");
}
// or
function camelize(string) {
return string.split('-').reduce(function(m, part) {
return m + part.charAt(0).toUpperCase() + part.slice(1);
});
}
// or
function camelize(string) {
var parts = string.split('-'),
result = ""
for (var i = 1; i < parts.length; i++) {
result += parts[i].charAt(0).toUpperCase() + parts[i].slice(1)
}
return result;
}

Related

How can I extract all contained characters in a String? [duplicate]

I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
if the letter doesn't repeat, it's not shown (it should be)
if it's repeated once, it's show only once (i.e. aa shows a - correct)
if it's repeated twice, shows all (i.e. aaa shows aaa - should be a)
if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa - should be a)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for is inside the first.
Fill a Set with the characters and concatenate its unique entries:
function unique(str) {
return String.prototype.concat.call(...new Set(str));
}
console.log(unique('abc')); // "abc"
console.log(unique('abcabc')); // "abc"
Convert it to an array first, then use Josh Mc’s answer at How to get unique values in an array, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = Array.from(nonUnique).filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line. :-)
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Per the actual question: "if the letter doesn't repeat its not shown"
function unique_char(str)
{
var obj = new Object();
for (var i = 0; i < str.length; i++)
{
var chr = str[i];
if (chr in obj)
{
obj[chr] += 1;
}
else
{
obj[chr] = 1;
}
}
var multiples = [];
for (key in obj)
{
// Remove this test if you just want unique chars
// But still keep the multiples.push(key)
if (obj[key] > 1)
{
multiples.push(key);
}
}
return multiples.join("");
}
var str = "aaabbbccc";
document.write(unique_char(str));
Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.
Try this if duplicate characters have to be displayed once, i.e.,
for i/p: aaabbbccc o/p: abc
var str="aaabbbccc";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 ){
return obj;
}
}
).join("");
//output: "abc"
And try this if only unique characters(String Bombarding Algo) have to be displayed, add another "and" condition to remove the characters which came more than once and display only unique characters, i.e.,
for i/p: aabbbkaha o/p: kh
var str="aabbbkaha";
Array.prototype.map.call(str,
(obj,i)=>{
if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){ // another and condition
return obj;
}
}
).join("");
//output: "kh"
<script>
uniqueString = "";
alert("Displays the number of a specific character in user entered string and then finds the number of unique characters:");
function countChar(testString, lookFor) {
var charCounter = 0;
document.write("Looking at this string:<br>");
for (pos = 0; pos < testString.length; pos++) {
if (testString.charAt(pos) == lookFor) {
charCounter += 1;
document.write("<B>" + lookFor + "</B>");
} else
document.write(testString.charAt(pos));
}
document.write("<br><br>");
return charCounter;
}
function findNumberOfUniqueChar(testString) {
var numChar = 0,
uniqueChar = 0;
for (pos = 0; pos < testString.length; pos++) {
var newLookFor = "";
for (pos2 = 0; pos2 <= pos; pos2++) {
if (testString.charAt(pos) == testString.charAt(pos2)) {
numChar += 1;
}
}
if (numChar == 1) {
uniqueChar += 1;
uniqueString = uniqueString + " " + testString.charAt(pos)
}
numChar = 0;
}
return uniqueChar;
}
var testString = prompt("Give me a string of characters to check", "");
var lookFor = "startvalue";
while (lookFor.length > 1) {
if (lookFor != "startvalue")
alert("Please select only one character");
lookFor = prompt(testString + "\n\nWhat should character should I look for?", "");
}
document.write("I found " + countChar(testString, lookFor) + " of the<b> " + lookFor + "</B> character");
document.write("<br><br>I counted the following " + findNumberOfUniqueChar(testString) + " unique character(s):");
document.write("<br>" + uniqueString)
</script>
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
The one line solution will be to use Set. const chars = [...new Set(s.split(''))];
If you want to return values in an array, you can use this function below.
const getUniqueChar = (str) => Array.from(str)
.filter((item, index, arr) => arr.slice(index + 1).indexOf(item) === -1);
console.log(getUniqueChar("aaabbbccc"));
Alternatively, you can use the Set constructor.
const getUniqueChar = (str) => new Set(str);
console.log(getUniqueChar("aaabbbccc"));
Here is the simplest function to do that pt. 2
const showUniqChars = (text) => {
let uniqChars = "";
for (const char of text) {
if (!uniqChars.includes(char))
uniqChars += char;
}
return uniqChars;
};
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on #le_m answer
let unique=myArray.filter((item,index,array)=>array.indexOf(item)===index)

How do I run a function over and over by using parameters?

My case:
function randomLetter(){
var random = letter[Math.floor(Math.random()*26)];
return random;
}
function randomWord(wordLength){
var random = randomLetter() + randomLetter() + randomLetter();
return random;
}
How do I write a code that run the randomLetter() function x times using parametes.
Example: I write 3 in the parameter, and the function will give me three random letters.
So instead of writing randomLetter() + randomLetter() + randomLetter(), I will just write randomWord(3), and I will get three random letters.
Another approach, which buffers each letter into an array and returns the joined array.
function randomWord(wordLength){
var letters = [];
for (var i = 0; i < wordLength; i++) {
letters.push(randomLetter());
}
return letters.join("");
}
Or recursion:
var letters = "abcdefghijklmnopqrstuvwxyz"
function randomLetter() {
return letters.charAt(Math.floor((Math.random() * 100)) % letters.length)
}
function getLetters(count) {
if (count-- < 1) return "";
return getLetters(count) + randomLetter() + ","
}
document.getElementById("output").innerText = getLetters(4)
<div id="output" />
For this you could use a for loop like:
function randomWord(wordLength){
var random =''
for (var i = 0, i<wordLength, i++) {
random += randomLetter();
}
return random;
}
the first parameter in the parentheses after the 'for' keyword initializes the i variable with 0. The next value i<wordLength is the stop condition, which will test at the beginning of each run if the condition is still true, otherwise it will stop looping. The third i++ is what runs every time a loop finishes, in this case it increments i by one, which is identical to i = i + 1.
here is some more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
You can use a for-loop:
function randomWord(x){
var random = [];
for(var a = 0; a < x; a++){
random[a] = randomLetter();
}
return random.join("");
}
Yet another recursive solution:
function randomLetter() {
return ('qwertyuiopasdfghjklzxcvbnm')[Math.floor(Math.random()*26)];
}
function randomWord(wordLength) {
return (wordLength > 0) ? (randomWord(wordLength - 1) + randomLetter()) : '';
}
console.log( randomWord(10) );

Is there a way to execute this code using a For Loop, just curious?

This code removes the space between names and inserts a comma. I am curious to know if there is a way to execute the same code using a For Loop in replace of "Split". I remember doing something similar but not enough to actually do it.
function cutName (name) {
return name.split(' ');
}
alert(cutName("Amjad Ali"));
Agree with the comments that what you are asking seems a bit weird, but here you go:
function cutName(name) {
let result = "";
for (let i = 0; i < name.length; i++) {
if (name[i] === " ") result += ",";
else result += name[i];
}
return result;
}
alert(cutName("Amjad Ali"));
This doesn't return an array as split() does, but the stringified result is the same (which appears to be what you are after).
If you do want an array, just like split(), try this instead:
function cutName (name) {
let result = [];
let lastIndex = 0;
for(let i=0; i<name.length; i++) {
if(name[i] === " ") {
result.push(name.substring(lastIndex, i));
lastIndex = i+1;
}
}
result.push(name.substring(lastIndex, name.length))
return result;
}
console.log(cutName("Amjad Ali"));
function cutName(name){
var result = "";
for(const char of name) result += char === " " ? "," : char;
return result;
}
console.log(cutName("Jonas W"));
You may use a for loop to iterate over every character.

Reducing duplicate characters in a string to a given minimum

I was messing around with the first question here: Reduce duplicate characters to a desired minimum and am looking for more elegant answers than what I came up with. It passes the test but curious to see other solutions. The sample tests are:
reduceString('aaaabbbb', 2) 'aabb'
reduceString('xaaabbbb', 2) 'xaabb'
reduceString('aaaabbbb', 1) 'ab'
reduceString('aaxxxaabbbb', 2) 'aaxxaabb'
and my solution (that passes these tests):
reduceString = function(str, amount) {
var count = 0;
var result = '';
for (var i = 0; i < str.length; i++) {
if (str[i] === str[i+1]) {
count++;
if (count < amount) {
result += str[i];
}
} else {
count = 0;
result += str[i];
}
};
return result;
}
Just use regular expressions.
var reduceString = function (str, amount) {
var re = new RegExp("(.)(?=\\1{" + amount + "})","g");
return str.replace(re, "");
}
I guess my best solution would be like
var str = "axxxaabbbbcaaxxxaab",
redStr = (s,n) => s.replace(/(\w)\1+/g,"$1".repeat(n));
console.log(redStr(str,2));
I tried to make it as short as possible:
reduceString = function(str, amount) {
var finalString = '', cL = '', counter;
str.split('').forEach(function(i){
if (i !== cL) counter = 0;
counter++;
cL = i;
if (counter <= amount ) finalString = finalString + i;
});
return finalString;
}
You can use reg expression instead. tested in javascript.
how it works:
(.) //match any character
\1 //if it follow by the same character
+{2 //more than 1 times
/g //global
$1 //is 1 time by $1$1 is 2 times
reduceString('aaaabbbb', 2)
reduceString('xaaabbbb', 2)
reduceString('aaaabbbb', 1)
reduceString('aaxxxaabbbb', 2)
function reduceString(txt,num)
{
var canRepeat=['$1'];
for (i=1;i<num;i++)
{
canRepeat.push('$1')
}
canRepeat = canRepeat.join('');
console.log(txt.replace(/(.)\1{2,}/g, canRepeat))
}
With regex:
var reduceString = function(str, amount) {
var x = [ ...new Set(str) ];
for (var c of x){
var rex = new RegExp(c + '{'+amount+',}','g');
str = str.replace(rex,string(c,amount));
}
return str;
};
var string = function(c,amount){
for(var i=0,s="";i<amount;i++)s+=c;
return s;
};
Up above regex solutions are much more better, but here is my accepted solution with reduce:
make an array from string via spread operator
Check the previous item
find how many times char is repeated in result string
otherwise concat result string with the current char
Don`t forget to use the second argument as the initial value, and return for each cases
reduceString = function(str, amount) {
return [...str].reduce(((res, cur)=>{
if(res.length && cur === res[res.length-1]){
dupsCount = [...res].filter(char => char === cur).length
if(dupsCount===amount){
return res;
}
else {
res+=cur;
return res;
}
}
res+=cur;
return res;
}),"")
}

Replace string in JS array without using native replace() method

I am stuck a bit with replacing string in js array. I am trying to log the arguments to see what is going on but am missing a piece of the puzzle.
fiddle
// - trying to look for substring in array
// - if match is found
// - replace substring without using the native method replace();
var div = $('.insert');
data = ["erf,", "erfeer,rf", "erfer"];
data = data.map(function (x) {
return /""/g.test(x) ? x.replace(/""/g, "") : x
});
function fakeReplace(data, substr, newstr) {
//should show ["erf,", "erfeer,rf", "erfer"];
div.append("data before match replace = " + data);
div.append("\<br>");
div.append("substr = " + substr);
div.append("\<br>");
div.append("newstr = " + newstr);
div.append("\<br>");
return data.split(substr).join(newstr);
}
fakeReplace(data, "erf", "blue");
//should show ["blue,", "blueeer,rf", "blueer"];
div.append("data after fakeReplace is executed = " + data);
You are treating data like a string in your function. You can use map() to return a new array with each element replaced.
function fakeReplace(data, substr, newstr) {
return data.map(function(s) {
return s.split(substr).join(newstr);
})
}
let myString = "Victor";
let splitted = myString.split('');
function replaceManual(a,b){
for(let i = 0; i<= splitted.length-1; i++)
{
for(let j=i; j <=i;j++)
{
if(splitted[j]===a)
{
splitted[j]=b;
return splitted;
}
else
{
break;
}
}
}
}
replaceManual('V','T');
console.log(splitted.toString().replace(/[^\w\s]/gi, ''));

Categories

Resources