JavaScript space-separated string to camelCase [duplicate] - javascript

This question already has answers here:
Converting any string into camel case
(44 answers)
Closed 8 years ago.
I've seen plenty of easy ways to convert camelCaseNames to camel Case Names, etc. but none on how to convert Sentence case names to sentenceCaseNames. Is there any easy way to do this in JS?

This should do the trick :
function toCamelCase(sentenceCase) {
var out = "";
sentenceCase.split(" ").forEach(function (el, idx) {
var add = el.toLowerCase();
out += (idx === 0 ? add : add[0].toUpperCase() + add.slice(1));
});
return out;
}
Explanation:
sentenceCase.split(" ") creates and array out of the sentence eg. ["Sentence", "case", "names"]
forEach loops through each variable in the array
inside the loop each string is lowercased, then the first letter is uppercased(apart for the first string) and the new string is appended to the out variable which is what the function will eventually return as the result.

Related

How can I found the index of a array of characters in a string without looping on the array characters [duplicate]

This question already has answers here:
Pass an array of strings into JavaScript indexOf()? Example: str.indexOf(arrayOfStrings)?
(4 answers)
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?
(22 answers)
Closed 1 year ago.
i'm searching a simple way to find the index of one character / string between a list of characters.
Something which looks like
"3.14".indexOf([".",","])
"3,14".indexOf([".",","])
Both should return 1.
One way:
const testRegex = /\.|,/
const match = testRegex.exec("3.14");
console.log(match && match.index)
It uses a regular expression to search for either character, and uses the exec method on regular expressions which returns an object that has the index of the start of the match.
You can loop through the array and return the first character's index whose index is not -1:
function getIndex(str, array){
for(e of array){
let index = str.indexOf(e);
if(index != -1){
return index;
}
}
}
console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))
You can also use Array.reduce:
function getIndex(str, array){
return array.reduce((a,b) => a == -1 ? a = str.indexOf(b) : a, -1)
}
console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))

How to create a function to split the following string? [duplicate]

This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));

I need a comprehensive regex to create a hyphened word chaining [duplicate]

This question already has answers here:
Regular rxpression to convert a camel case string into kebab case
(4 answers)
Closed 2 years ago.
The aim of the challenge is to create a hyphened word chaining. My question is how I could create an all-encompassing regex for the scenarios shown below:
I am able to do the first, third and fourth example.
function spinalCase(str) {
let result =str.toLowerCase().split(/\W/)
result.join('-')
return result;
}
spinalCase('This Is Spinal Tap');
spinalCase("Teletubbies say Eh-oh");
spinalCase("The_Andy_Griffith_Show");
spinalCase("thisIsSpinalTap")// My code does not work on these
spinalCase("AllThe-small Things")// My code does not work on these
You can use the following regular expression:
Reference: https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-123.php
var spinalCase = function(str) {
var converted = str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('-');
console.log(converted)
return converted;
};
spinalCase('This Is Spinal Tap');
spinalCase("Teletubbies say Eh-oh");
spinalCase("The_Andy_Griffith_Show");
spinalCase("thisIsSpinalTap")
spinalCase("AllThe-small Things")

How to convert object array to comma separated string? [duplicate]

This question already has answers here:
Transform Javascript Array into delimited String
(7 answers)
Closed 4 years ago.
Im trying to convert at object array with jQuery or javascript to a comma separated string, and no matter what I try I canĀ“t get it right.
I have this from a select value.
ort = $('#ort').val();
ort=JSON.stringify(ort)
ort=["Varberg","Halmstad","Falkenberg"]
How can I convert it to a string looking like this?
ort=Varberg,Halmstad,Falkenberg
Any input appreciated, thanks.
You can use join
let arr = ["Varberg","Halmstad","Falkenberg"]
console.log(arr.join(','))
Use Array.prototype.join to to convert it into a comma separated string.
let str = ort=["Varberg","Halmstad","Falkenberg"].join(","); //"," not needed in join
console.log(str);
A simple toString also works in this case.
let str = ort=["Varberg","Halmstad","Falkenberg"].toString();
console.log(str);
Another way to achieve this is by using Array.prototype.reduce:
console.log(["Varberg", "Halmstad", "Falkenberg"].reduce((s, el, idx, arr) => {
s += el
if (idx < arr.length - 1) {
s += ','
}
return s;
}, ''));

Use regex to replace lower case values to title Case JavaScript [duplicate]

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 4 years ago.
I want to use regex to replace the lowercase letter of every word within a string of words, with an uppercase, ie change it to title case such that str_val="This is the best sauce ever"
becomes "This Is The Best Sauce Ever".
Here is my code
function (str_val) {
let reg_exp = /\s\w/g;
let str_len = str_val.split(' ').length;
while (str_len){
str_val[x].replace(reg_exp, reg_exp.toUpperCase());
x++;
str_len--;
}
return str_val;
}
How do I solve this with regex?
Use below function for title case
function title(str) {
return str.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}

Categories

Resources