This question already has answers here:
Converting Odd and Even-indexed characters in a string to uppercase/lowercase in Javascript?
(4 answers)
Closed 5 years ago.
I'm trying to write a for loop to capitalize every other letter of a string. Here's what I've come up with so far..
var input = "craig";
document.getElementById("para").innerHTML = firstLetterUppercase();
function firstLetterUppercase () {
for (i=0; i < input.length; i+=2) {
input.charAt(i).toUpperCase;
return input;
}
}
<p id="para"> </p>
Why won't this work? Any Thoughts?
Strings in javascript are immutable. You cannot modify original string. You'll have to create a new one:
function firstLetterUppercase (input) {
var res = "";
for (i=0; i < input.length; i++) {
res += i % 2 == 0 ? input.charAt(i).toUpperCase() : input.charAt(i);
}
return res;
}
var test = 'test string';
console.log(firstLetterUppercase(test));
return keyword inside the for loop aborts it just right after the first cycle.
toUpperCase is a function, you have to execute it on specified element, using ().
input.charAt(i).toUpperCase() will return new changed letter, without mutating the original one.
Instead of binding the whole function to the DOM element, bind just the returned variable.
I would suggest you to split the string or just use the spread operator, then map it using Array#map to change only letters with even index.
var input = "craig",
elem = document.getElementById("para");
function firstLetterUppercase() {
elem.innerHTML = [...input].map((v,i) => i%2 ? v : v.toUpperCase()).join('');
}
firstLetterUppercase();
<p id="para"></p>
input.charAt() wont modify the string in place, so you'll need to assign the result to something. There were also a few other problems, but here's something that rather resembles what you had, but works:
function firstLetterUppercase (input) {
for (i=0; i < input.length; i+=2) {
input = input.substr(0, i) + input[i].toUpperCase() + input.substr(i + 1);
}
return input;
}
var test = 'this is a test';
console.log(firstLetterUppercase(test));
Here's another version using a regex:
var test = 'this is a test123';
function firstLetterUppercase() {
return test.replace(/.{2}/g, function(match, $1, $2, offset, original) {
return '' + match[0].toUpperCase() + match[1];
})
}
console.log(firstLetterUppercase(test));
Related
I am brand new to Javascript and trying to figure out how to camel-case any string by using a for loop. This is what I have so far.
function camelCase(str) {
var splitStr = "";
var result = "";
splitStr = str.split(" ");
for(var i = 0; i < splitStr.length; i++){
result += splitStr[i][0].toUpperCase() +
splitStr[i].slice(1);
}
return result;
}
console.log(camelCase("hello there people"));
it returns "HelloTherePeople" - How do you I make the very first index of splitStr (splitStr[0][0]) be excluded from toUpperCase, but still included in the beginning of the string?
What is your delimiter? This method assumes an underscore _. Change it to a space if you want a space. Or make it a variable you can pass to camelize.
if( !String.prototype.camelize )
String.prototype.camelize = function(){
return this.replace(/_+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
}
"a_new_string".camelize()
//"aNewString"
The regex /_+(.)?/g/ says find 1 or more _ characters followed by any character ., the (.) creates a capturing group, so you are able to get that one character. It's passed to the function as the second paramater chr. The ? means not greedy so it will stop at the next _. The g means globally, pretty much means find all matches.
String.prototype.replace reference
change return like this:
return result[0].toLowerCase()+result.substr(1);
You can do a check inside the loop to see if you are on the first index.
function camelCase(str) {
//splitStr will be an array
var splitStr = [];
var result = "";
splitStr = str.split(" ");
//Capitalize first letter of words starting from the second one
for(var i = 0; i < splitStr.length; i++){
//first word
if (i===0) {
//Good practice to lowercase the first letter regardless of input
result += splitStr[i][0].toLowerCase() + splitStr[i].slice(1);
}
else {
//rest can proceed as before
result += splitStr[i][0].toUpperCase() +
splitStr[i].slice(1);
}
}
return result;
}
console.log(camelCase("hello there people"));
Alternatively, the loop can even start on the second index. However, you will have to check if the length of splitStr before running a loop from the second index
This question already has answers here:
The .replace() method does change the string in place [duplicate]
(3 answers)
Closed 4 years ago.
So, I'm working on some exercise questions. My code seems to be working fine up until I decide to loop through the string to replace any instance of a period with nothing. For some reason, the loop doesn't work. I imagine it has something to do with not calling it somehow, but I'm not sure how to call the loop. I thought that loops automatically overwrote what they are looping through. Here is the exercise and my incomplete solution:
Write a JavaScript function to parameterize a string.
function string_parameterize(string) {
var lowercase_string = string.toLowerCase();
var split_string = lowercase_string.split(" ");
var joined_string = split_string.join("-");
for (i = 0; i < joined_string.length; i++) {
if (joined_string[i] === ".") {
joined_string[i] === "";
}
}
return joined_string;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
The answer should be robin-singh-from-usa without the period, but it keeps coming out as robin-singh-from-usa. with the period.
The other answers are not taking into account that strings in JavaScript are immutable. You can not change individual characters in a string. You build a new string.
In JavaScript, strings are immutable. Trying to change the characters in a string does not work:
function string_parameterize(string) {
var lowercase_string = string.toLowerCase();
var split_string = lowercase_string.split(" ");
var joined_string = split_string.join("-");
for (i = 0; i < joined_string.length; i++) {
if (joined_string[i] === ".") {
joined_string[i] = "";
}
}
return joined_string;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA.")); //This will not work:
You can build a new string using your for loop to individually add each character that is not a . to the newString:
function string_parameterize(string) {
var lowercase_string = string.toLowerCase();
var split_string = lowercase_string.split(" ");
var joined_string = split_string.join("-");
var newString = '';
for (i = 0; i < joined_string.length; i++) {
if (joined_string[i] !== ".") {
newString += joined_string[i];
} //We are replacing '.' with nothing, '', so no need for an else
}
return newString;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
Regular Expressions
This would, however, normally be done with Regular Expressions, specifically the .replace() method:
function string_parameterize(string) {
var lowercase_string = string.toLowerCase();
var newString = lowercase_string.replace(/ /g,'-'); //Replace all spaces with '-'.
var newString = newString.replace(/\./g,''); //Replace all '.' with nothing. The '.'
// has to be quoted with \. as it
// has special meaning in a RegExp.
return newString;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
Which can be done all in one statement:
function string_parameterize(string) {
return string.toLowerCase().replace(/ /g,'-').replace(/\./g,'');
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
You can put in a [...]+ every character you don't want have in the output.
var res = string.toLowerCase().replace(/[%\(\)\.\s]+/g, "-").replace(/-$/, "");
// ^ ^ ^ ^
// Here the characters you don't want to have in the output
+ means matched one ore more times. Replace the matched characters with -.
Then remove last - with -$.
In total
function string_parameterize(string) {
var res = string.toLowerCase().replace(/[%\(\)\.\s]+/g, "-").replace(/-$/, "");
return res;
}
console.log(string_parameterize("Это тест")); // A russian sentence
console.log(string_parameterize("Robin Singh%%() from USA. "));
console.log(string_parameterize("Robin ...Singh from USA....."));
console.log(string_parameterize("Robin Singh from USA "));
console.log(string_parameterize("Robin Singh from USA"));
Info about regular expression.
function string_parameterize(string) {
var lowercase_string = string.toLowerCase();
var split_string = lowercase_string.split(" ");
var joined_string = split_string.join("-");
joined_string = joined_string.replace(".", "");
return joined_string;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
This is working in IE.
function string_parameterize(str){
return str.toLowerCase().replace(".", "").split(" ").join("-");
}
console.log(string_parameterize("Robin Singh from USA."));
//will result in: robin-singh-from-usa
Your code is not working because in if condition you are checking for joined_string[i]==="." to be equal to '.' and actually it is equal to 'USA.'. That is why this if condition never met with and return the '.' in the final result:
if (joined_string[i]===".") {
joined_string[i]==="";
}
You're checking the value of joined_string[i], rather than assigning it.
joined_string[i] = "";
not
joined_string[i] === "";
Change:
if (joined_string[i]===".") {
joined_string[i]==="";
}
to
if (joined_string[i]===".") {
joined_string[i]="";
}
I have an string, but at certain points in the string it has dynamic values.
I want to find those points in the string and replace them with values from an array.
Let's say I have:
var array = ['string', 'value'];
var string = 'This is a {1}, and this is a {2}.';
Now I need to figure out a way to replace {1}, with the value of the first index in the array and replace {2} with the value of the second index of the array.
So the string would like this:
This is a string, and this is a value.
This seems so simple, but I am breaking my head on this. I can't find a way to do this easily.
You can use replace with a regular expression and a function:
string.replace(/{(\d+)}/g, function(match, n) {
return array[n-1];
});
You can also check n < 1 || n > array.length to provide a fallback value in case the number is out of bounds.
Alternatively, the new ES6 way is using tagged template strings
function tag(strings, ...values) {
var parts = [];
for(var i=0; i<strings.length; ++i)
parts.push(strings[i], array[values[i]-1]);
return parts.join('');
}
tag`This is a ${1}, and this is a ${2}.`
like this
string.replace(/\{(\d+)\}/g, function(m, n){
return array[n-1]
})
You can use Array.prototype.reduce:
var StringHelper = {
format: function(format, args) {
return args.reduce(function(result, currentReplace, currentReplaceIndex) {
result = result.replace("{" + (currentReplaceIndex + 1) + "}", args[currentReplaceIndex]);
return result;
}, format);
}
};
var sourceString = "My name is {1} and I'm {2} years old";
var replaceItems = ["Matías", "31"];
var parsedString = StringHelper.format(sourceString, replaceItems);
alert(parsedString);
It's a good alternative to regular expressions, and I'm not absolutely sure if I did a jsPerf test in the right way, but it shows that this approach outperforms the regular expression one.
I am trying to use the prototype method of writing functions that can be implemented by strings to capitalise every first letter of every word. I would like to call this function like,
var str = "Example of a string";
str.toJadenCase();
This is the function I am trying to write:
String.prototype.toJadenCase = function () {
//split the statement into each word
if (String.prototype.length !== 0)
{
var eachWord = String.prototype.split(" ");
var n = eachWord.length;
if(n !== 0)
{
//loop through the array of words
for(var i = 0; i < eachWord.length; i++){
//for each loop, split the word into individual characters
var charArray = eachWord[i].split("");
//capitalise the first element of character array
charArray[0] = charArray[0].toUpperCase();
//join all elements in character array to string
eachWord[i] = charArray.join("");
}
//join all the words to form the statement
String.prototype = eachWord.join(" ");
return String.prototype;
}
}
};
I had written it this way before:
var capitaliseInitial = function(sampleText){
var textString = sampleText;
//split the statement into each word
var eachWord = textString.split(" ");
//loop through the array of words
for(var i = 0; i < eachWord.length; i++){
//for each loop, split the word into individual characters
var charArray = eachWord[i].split("");
//capitalise the first element of character array
charArray[0] = charArray[0].toUpperCase();
//join all elements in character array to string
eachWord[i] = charArray.join("");
}
//join all the words to form the statement
textString = eachWord.join(" ");
return textString;
}
I would like to call this function like,
var str = "Example of a string";
str.toJadenCase();
You can't, strings are immutable. You would have to call it like this:
str = str.toJadenCase();
In your function, you're using String.prototype incorrectly. String.prototype is the object containing the various String-specific methods. It's assigned as the underlying prototype of all strings.
Where you're using String.prototype, you should be using this, and instead of trying to assign to it (this = ... is invalid), return the result.
The simple way to do what you're doing is to:
Split the string into an array of words, as you have
Loop through that array either building up a new string with the capitalized words via +=, or building a new array with the capitalized words and then doing Array#join at the end to put it back together.
Return the string you built
Something like this:
String.prototype.toJadenCase = function() {
var result = this;
//split the statement into each word
if (this.length !== 0) {
result = this.split(" ").map(function(word) {
return word.substring(0, 1).toUpperCase() + word.substring(1);
}).join(" ");
}
return result;
};
snippet.log("this is a test".toJadenCase());
snippet.log("oneword".toJadenCase());
snippet.log("blank: " + ("".toJadenCase()));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note I've done away with the check if the array of words' length isn't 0: It can't be 0 if you've pre-checked the length as you have.
use RegExp and php like naming
str.ucwords()
String.prototype.ucwords = function() {
return this.replace(/\b\S/g,function(c){
return c.toUpperCase()
}
}
Here's how I did mine.
Split the string into an array of words, as you have
Loop through that array either building up a new string with the capitalized words via +=, or building a new array with the capitalized words and then doing Array#join at the end to put it back together.
Return the string you built
String.prototype.toJadenCase = function () { return this.split(" ").map(function(word){ return word.charAt(0).toUpperCase() + word.slice(1); }).join(" "); }
This look like one of the Code Wars Katas - this was my solution -
String.prototype.toJadenCase = function () {
// assign 'this' keyword to a variable and split String into an array
var result = this.split(" ");
/* loop through the array changing first character of each item to
uppercase & adding it to the remaining letters in each item */
for(i = 0; i < result.length; i++) {
result[i] = result[i].charAt(0).toUpperCase() + result[i].substring(1);
}
//finally return items joined back together in a string
return result.join(' ');
};
another way to do this would be like:
String.prototype.toJadenCase = function() {
return this
.split(" ")
.map(i => i.replace(i[0], i[0].toUpperCase()))
.join(" ");
};
I am trying to pass a number string through a function that iterates through each character, wrapping each in a element if it is or is not a number.
var str = "$6,117,766.69";
var nonNumber = "$,.";
for (var i = 0; i < str.length; i++) {
if (nonNumber.contains(str[i])) {
$('body').append("<span class = 'thecolorYellow'>"+str[i]+"</span>");
} else {
$('body').append("<span class = 'thecolorBlue'>"+str[i]+"</span>");
}
}
My question is this: How can I make this a function that returns this as a string instead of modifying the DOM? And second, how could I adapt this function to make sure that characters outside of 0-9 and the three non-numerics are omitted from the final string?
I'd suggest you use replace to generate the markup, then you can append it all at once:
var html = str.replace(/./g, function(match) {
var clas = isNaN(match) ? 'yellow' : 'blue'
return '<span class="'+ clas +'">'+ match +'</span>'
})
$('body').append(html)
function getAmountAsNumber(dollarAmount)
{
return dollarAmount.replace(/\D/g,'');
}
The above function will return just the digits 0-9 from your input string and will also make sure that all your non-numeric characters are ommitted.