how to convert passed string to Camel Case - javascript

Hi I'm working on a problem that requires me to 'returns the passed string convertedToCamelCase'
I tried doing it like this
let wordsArr = words.toLowerCase().split(" ")
for (let i = 1; i<wordsArr.length; i++){
wordsArr[i] = wordsArr[i].charAt(0).toUpperCase()
wordsArr.slice(1)
}
return wordsArr.join("")
but that doesnt seem to work and now im stuck

Something like this should work if it doesn't contain punctuation
let camelot = "I have to push the pram a lot";
const makeCamel = s => {
let camelArray = s.toLowerCase().split(' ')
let newArray = [camelArray[0]]
for (let i in camelArray) {
if (i >= 1) {
let capLetter = camelArray[i][0].toUpperCase()
let rest = camelArray[i].slice(1);
let newWord = capLetter + rest
newArray.push(newWord);
}
}
return newArray.join('');
}
makeCamel(camelot)

Related

Finding the index of several identical words

I have a laTeX string like this
let result = "\\frac{x}{2}+\\frac{3}{x}";
I want to find the index of "frac"s in the string and put them in a array then I want to find the first '}' char after "frac" and replace it with "}/" and finally remove "frac" from the string.
I used this block of code but it just work correctly when we have one "frac"
let result = "\\frac{x}{2}+\\frac{3}{x}";
if (result.indexOf("frac") != -1) {
for (let i = 0; i < result.split("frac").length; i++) {
let j = result.indexOf("frac");
let permission = true;
while (permission) {
if (result[j] == "}") {
result = result.replace(result[j], "}/")
permission = false;
}
j++;
}
result = result.replace('frac', '');
}
}
console.log(result)
OUTPUT: \\{x}//{2}+\\{3}{x}
Could anyone help me to improve my code?
Something like this?
frac(.+?)}
is the literal frac followed by a capture group that will capture one or more of anything .+ until a } and replace it with that anything plus a }/
Using the function replacement to grab index and replace
let result = "\\frac{x}{2}+\\frac{3}{x}";
let pos = [];
const newRes = result.replace(/frac(.+?)}/g,function(match, found, offset,string) {
console.log(match,found,offset,string)
pos.push(offset)
return `${found}/`; // return the found string with the added slash
})
console.log(pos)
console.log(newRes)
Older answer using two sets of code
let result = "\\frac{x}{2}+\\frac{3}{x}";
let re = /frac/gi, res, pos = [];
while ((res = re.exec(result))) {
pos.push(res.index);
}
const newRes = result.replace(/frac(.+?)}/g,"$1}/")
console.log(pos)
console.log(newRes)

Getting string in quotes in javascript

How may I write a function to get all the strings in quotes from a string? The string may contain escaped quotes. I've tried regex but as regex does not have a state like feature, I wasn't able to do that. Example:
apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"
should return an array like ['pear', '"tomato"', 'i am running out of fruit" names here']
Maybe something with split can work, though I can't figure out how.
I solved this problem using the following function:
const getStringInQuotes = (text) => {
let quoteTogether = "";
let retval = [];
let a = text.split('"');
let inQuote = false;
for (let i = 0; i < a.length; i++) {
if (inQuote) {
quoteTogether += a[i];
if (quoteTogether[quoteTogether.length - 1] !== '\\') {
inQuote = false;
retval.push(quoteTogether);
quoteTogether = "";
} else {
quoteTogether = quoteTogether.slice(0, -1) + '"'
}
} else {
inQuote = true;
}
}
return retval;
}
Try this:
function getStringInQuotes(text) {
const regex = const regex = /(?<=")\w+ .*(?=")|(?<=")\w+(?=")|\"\w+\"(?=")|(?<=" )\w+(?=")|(?<=")\w+(?= ")/g
return text.match(regex);
}
const text = `apple banana "pear" strawberries "\"tomato\"" "i am running out of fruit\" names here"`;
console.log(getStringInQuotes(text));

Combines two arrays into one sentence

I'm new in javascript and I don't know how to merge some array. I want to reverse word manually but I mess up. It's my code:
function reverseString(kata) {
let currentString = kata;
let newString = '';
let cetakKata = '';
for (let i = kata.length - 1; i >= 0; i--) {
newString = newString + currentString[i];
}
console.log(newString);
const splitNewString = newString.split(' ')
console.log(splitNewString);
for (let i = 0; i < splitNewString.length; i++) {
const cetak = splitNewString[i].split('').reverse().join('')
cetakKata = cetakKata + cetak
}
console.log(cetakKata);
}
reverseString('hello java script');
my output:
scriptjavahello
output I want:
script java hello
function ReversedStringSentence (stringData) {
return stringData.split(" ").reverse().join(" ");
}
ReversedStringSentence("I am Greater everyday")
Reverse without .reverse()
reverseString('hello java script');
function reverseString(kata) {
let splited = kata.split(' ');
let reversed = [];
for (let i = 0; i < splited.length;i++) {
reversed.push(splited[(splited.length - 1) - i ]);
}
let stringReversed = reversed.join(' ');
console.log(stringReversed);
}
You probably wants to learn javascript and that's why you're doing it like you do, but there are already functions that does what you're trying to do.
arr.reverse() // reverses array
I don't know how many programming languages that you have learned, but what works best for me is to just read through all documentation so I know what kind of options I have at hand. I won't remember it all, but I will recognize them when I have to search for solutions.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript
function reverseString(kata) {
const AT_SPACE = ' ';
return kata
.split(AT_SPACE)
.reverse()
.join(AT_SPACE);
}
let reversedKata = reverseString('hello java script');
console.log(reversedKata)

How can I match a word inside of a string to word in a list EXACTLY?

I have been playing around with a pokemon API for a couple of days.
I have an array with all pokemon listed and have a string that looks something like this '<#user_id pidgeotto>'
I would like to check this string, against an array and get that EXACT name
My issue is that I ALSO get things that would be included, like pidgeot.
How can I match the array exactly to the string and ONLY log the one name?
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (y.includes(message[i])) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
No errors, just not getting the result I am looking for.
Split the y string at the space and see if second part is exact using === comparison
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
let yName = y.split(' ')[1];
function handleMessage(message) {
for (let i = 0; i <= message.length; i++) {
if (message[i] === yName ) {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
you could do it by this way to avoid the first element in PokemonArray
let pokemonArray = ["pidgeot", "pidgeotto", "charizard", "goldeen"];
let y = '<#user_id> pidgeotto';
function handleMessage(message) {
for(let i = 0; i <= message.length; i++) {
let splitedY = y.split(message[i])
if(splitedY.length > 1 && splitedY[1] !== "") {
console.log(message[i])
}
}
}
handleMessage(pokemonArray);
Here is the one liner for this:
const match = pokemonArray.find(pokemon => new RegExp(`\\b${pokemon}\\b`, `i`).test(y));
Simply use array find method and match your string using regex.
Hope this helps :)

Checking if Palindrome Program Always Returns True

Sorry for the awkward formatting. I wrote this palindrome checking program and can't figure out why it always returns true. The 'word'refers to an intake through html and so does 'reportIfPalindrome'. Values are intaked and displayed so there is no problem with the html. Any help is appreciated
const wordBox = document.getElementById('word');
wordBox.addEventListener('input', checkIfPalindrome);
function checkIfPalindrome() {
const word = wordBox.value;
const allCaps = word === word.toUpperCase();
const outsideTrim = allCaps === word.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
document.getElementById('reportIfPalindrome').innerHTML = result;
}
There are quite a few flaws in your code. First, you are storing booleans for the variables where you seemingly intend to store the capitalized and trimmed words. Secondly, you are not running the loop with the right boundary conditions. See the updated snippet below.
checkIfPalindrome();
function checkIfPalindrome() {
const word = "aBa";
const allCaps = word.toUpperCase();
const outsideTrim = allCaps.trim();
let completelyTrimmed = "";
let individualCharacter = "";
for(x=0; x<outsideTrim.length; x++)
{
individualCharacter = outsideTrim.substring(x, x+1)
completelyTrimmed+= individualCharacter === " "? "": individualCharacter;
}
let reverseString = ""
for (x=completelyTrimmed.length-1; x>=0; x--){
reverseString = reverseString + completelyTrimmed.substring(x, x+1);
}
let result = completelyTrimmed===reverseString;
//document.getElementById('reportIfPalindrome').innerHTML = result;
console.log(result);
}

Categories

Resources