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.
Related
I'm trying to do a challenge which is converting all strings into camelCase but without using regex, only using the methods like(split, slice, replace, includes.. etc). Some words have spaces and should remove them. Here's the CODE and I'm really STUCK. NOTE: the user enters the STRING and when user clicks the button should return to the camelCase.
INPUT =>
//underscore_case
//first_name
//Some_Variable
// calculate_AGE
//delayed_departure
OUTPUT =>
//underscoreCase
//firstName
//someVariable
//calculateAge
//delayedDeparture
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function() {
const text = document.querySelector('textarea').value;
const row = text.split('\n');
let [...n] = '';
for (const theText of row) {
const lowerText = theText.toLowerCase().trim();
if (lowerText.includes('_')) {
n = lowerText.replace('_', ' ');
console.log([...n]);
}
}
});
Explanation of this simple algorithm:
Your input must have words that split by a certain character, as you need something to identify which part of the string is a word. Let's assume your string has words separated by '//' instead of spaces as you mentioned in the comments, and each of those words is split by '_'.
First you need to split all words in the string into an array, you can use the split() method in order to do that.
Then when iterating through each word, split it again with split() but this time with whatever identifies the different words, in our case it's _.
Iterate through each split words, if it's the first word lowercase it using toLowerCase() and add it to the new word variable, if not, lowercase it and capitalize the first letter.
And that's it. Here's the implementation:
const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR'
function stringToCamelCase(string) {
const allNames = string.split('//')
let camelCasedString = '';
for (const name of allNames) {
camelCasedString += nameToCamelCaseHelper(name);
}
return camelCasedString;
}
function nameToCamelCaseHelper(word) {
const splittedName = word.split('_');
let camelCasedName = '';
for (let i = 0; i < splittedName.length; i++) {
if (i === 0) {
camelCasedName += splittedName[i].toLowerCase();
} else {
camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase())
}
}
return camelCasedName;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar
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:
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));
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 want to know if the code below removes all input type='text' values back to "":
var inp = document.getElementsByTagName('input');
for (var i = inp.length - 1; i >= 0; i--) {
if ('text' === inp[i].type) inp[i].value = "";
}
Then I want to know if I have an input which is type='text' but which class is .num_questions. How can I code that so that it looks for the class name and gives it a value of "1"?
There is a property className on the Html Dom Element.
function hasCssClass(elt,clz) {
return elt.className.match(new RegExp('(\\s+|^)'+clz+'(\\s+|$)'));
}
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type && hasCssClass(inp[i],'num_questions')) {
inp[i].value = "?";
}
}
http://jsbin.com/aluzuv/2
EDIT - followup as requested.
Each HTML DOM Element has a className property, which is a string, containing a list of whitespace-separated CSS classes that apply to the element. In order to determine if a class applies to a particular element, you need to search for that string, in the list.
There are a couple ways to do it. One way is to split the className string by whitespace, and then see if your desired class (needle) is equal to any of the elements in the resulting string array. This might be something like this:
function hasCssClass(elt, clz) {
var classes = elt.className.split(/\s+/);
for(i=0; i<classes.Length;i++) {
if (clz == classes[i]) return true;
}
return false;
}
Another way is to use a regex match; that's what I did, because to me it's more succint. The regex I used looks for something, followed by the classname, followed by something else. The first something is (\\s+|^) , which in English means "one or more whitespace characters, OR, the beginning of the string." The something else is (\\s+|$), which in English is, "one or more whitespace characters, OR the end of the string." Therefore, the entire regex matches a string which consists of:
whitespace or beginning-of-string
desired classname
whitespace or end-of-string
Well, i don't think your question should be downvoted, handling classNames is not easy in javascript. So here is my answer:
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type) {
if(inp[i].className.indexOf('num_questions') > -1){
inp[i].value = "1";
} else{
inp[i].value = "";
}
}
}