Change first letter in string to uppercase in JavaScript - javascript

I have an array of strings,
["item1", "item2"]
I'd like to change my array to
["showItem1", "showItem2"]

The most easy to understand way of doing exactly what you ask for is probably something like this:
var items = ["item1", "item2"];
​for (var i=0;i<items.length;i+=1) {
items[i] = "show" + items[i].charAt(0).toUpperCase() + items[i].substring(1);
}
console.log(items); // prints ["showItem1", "showItem2"]
Explanation: build a new string consisting of the string "show" + the first character converted to uppercase + the remainder of the string (everything after the first character, which has index 0)

Strings are array-like. You could do this:
var arr = ['item1', 'item2'];
for (var i=0, l=arr.length; i<l; i++) {
var letters = arr[i].split('');
arr[i] = 'show' + letters.shift().toUpperCase() + letters.join('');
}
Demo: http://jsbin.com/asivec/1/edit

arr.map(function(i) {
return 'show' + i.charAt(0).toUpperCase() + i.slice(1);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
supported in Chrome, Firefox, IE9 and others.

Here is a reusable firstCharLowerToUpper() function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
span{
color:red;
}
</style>
</head>
<body>
<div>this is the text:
<span id="spn">
javascript can be very fun
</span>
</div>
<br/>
<input type="button" value="Click Here" onClick="change()"/>
<script>
function firstCharLowerToUpper(x)
{
var ar = x;
for (var i = 0; i < ar.length; i++)
{
ar[i] = ar[i].charAt(0).toUpperCase() + ar[i].substr(1);
}
// join to string just to show the result
return ar.join('\n');
}
function change()
{
var ar = ["javascript ", "can ","be ","very ","fun" ];
var newtxt = firstCharLowerToUpper(ar);
document.getElementById("spn").innerHTML = newtxt;
}
</script>
</body>
</html>

Related

JavaScript/HTML: find longest word and compare to current word

I'm writing a code that :
Allow my user to type in a sentence.
Find the longest word in that sentence.
Compare that longest one to every word in the sentence.
The words of the string directly out to a webpage, laid out so that no
single line is longer than the longest word in the string.
I've been working this code for two days and feel like completely lost in somewhere. Please advise me to improve my code.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to currend word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for ( i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthofString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var x = 0;
var testLength = 0;
var testLength = arrayOfText[i].length;
do {
testLength + 1 + arrayOfText[i].length
} while (testLength > longWord);
}
//Call this function in HTML
function wrapText(string) {
var length = longWord(string);
layoutString(string, length);
document.getElementById("demo").innerHTML += arrayOfText + "<br>";
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>
Some issues:
arrayOfText is not accessible in layoutString and wrapText as it is a locale variable of longWord
In layoutString you use longWord (the function name) instead of the parameter length.
The line "testLength + 1 + arrayOfText[i].length" has no effect, it just adds the three values together but does not assign it to anything.
layoutString generally does nothing ...
I'm not sure about your 4th requirement as all words' length will be less or equal than the longest word's length, so I add hyphens in front of all shorter words so they are all the same length. Maybe that gets you closer to your final goal.
Try this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to current word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthOfString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
while (arrayOfText[i].length < length) {
arrayOfText[i] = '-' + arrayOfText[i];
};
}
return arrayOfText;
}
//Call this function in HTML
function wrapText(string) {
var longestWordLength = longWord(string),
strings = layoutString(string, longestWordLength),
demo = document.getElementById("demo");
demo.innerHTML = '';
for (var i = 0; i < strings.length; i++){
demo.innerHTML += strings[i] + "<br>";
}
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>

Sorting data in a stored array

Below is my code. I need to sort the array after the user input but can't figure out how to make that happen. I have tried several different things but nothing has worked including data.sort() and data.sort(function(a,b) { return a - b; }); but neither seems to be working. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Input integers into the array and then search the array to see if your input is present!</h1>
<p id="data">[]</p>
<input id="inputNumber" value="0" /> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0" /> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
for (var i = 0; i < 5; i++) {
data.push(prompt('enter integer ' + (i + 1)));
}
alert('Full array: ' + data.join(', '));
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for (var i = 0; i < data.length; i++) {
if (data[i] == toFind) return alert("found at " + i);
}
return alert("That number was not found");
}
function refresh() {
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>

JS. How do I create a regex pattern by concatenation with variables

I am not able to fix the following:
<html>
<head>
<title>Test</title>
<script>
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('/^[A-z]et_[' + s + ']_\\d/');
// NOTE I get the following, is that how it should be?
// window.alert(pattern); => /\/^[A-z]et_[0]_\d\//
// NOTE: I checked that it works fine for a single digit case, say:
// var pattern = new RegExp(/^[A-z]et_[3]_\d/);
var newarr = arr.filter(elt => pattern.test(elt));
document.getElementById("demo").innerHTML = newarr;
}}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
I see many similar questions, but I have not been able to find out how to fix my code. It should be possible, shouldn't it?
EDIT
the following is what I need:
<html>
<head>
<title>Test</title>
<script>
var newarr = [];
function myFunction(arr) {
var N = [0,1,2,3,4,5,6,7,8,9];
for (var s in N) {
var pattern = new RegExp('^[A-z]et_' + s + '_\\d'); // NOTE: not /
var lnewarr = arr.filter(elt => pattern.test(elt));
if(typeof lnewarr !== 'undefined' && lnewarr.length > 0){newarr.push(lnewarr)};
}
document.getElementById("demo").innerHTML = newarr;
}
</script>
</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>
(sorry if my post is mostly code. Hope it may helps somebody out there.)
Instead of for loop you can use a .join like this:
var pattern = new RegExp('^[A-Za-z]et_[' + N.join('') + ']_\\d');
//=> /^[A-Za-z]et_[0123456789]_\d/
This works for the case when you have singe character values in your array N.
For generic use you can use this expression:
var pattern = new RegExp('^[A-Za-z]et_(?:' + N.join('|') + ')_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/
Using a for loop you can do this:
var N = [0,1,2,3,4,5,6,7,8,9];
var str='(?:';
for (var s in N)
str += s + '|';
str = str.replace(/\|$/, ')');
var pattern = new RegExp('^[A-Za-z]et_' + str + '_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

How to make a list randomizer

I have been working on a fairly pointless website where there are multiple "random" generators. You can check it out here: randomwordgen.net16.net
As you can see there is an unfinished generator at the bottom, that's what I'm here for. I want to get it to generate a list from things you input. My idea is to add the input field's value to the array that will make the list when you hit "Add to List." Then I will have a separate button that will generate the list using that array. The only problem is that I don't know how to add the string to the array when I only know the name of the variable, not the value. If anyone could help me with any of this, that would be great!
This is the code for the whole site:
<!DocType html>
<html>
<head>
<link rel="shortcut icon" href="https://cdn2.iconfinder.com/data/icons/thesquid-ink-40-free-flat-icon-pack/64/rubber-duck-512.png" type="image/x-icon">
<title>Random Word Generator</title>
<style>
body {
background-color:pink;
}
button.10letter {
background-color: blue;
}
button.5letter {
background-color: blue;
position:relative;
top:50px;
}
button.4letter {
background-color: blue;
position:relative;
top:100px;
}
button.3letter {
background-color: blue;
position:relative;
top:150px;
}
button.Add {
position:relative;
top:50px;
}
</style>
</head>
<body>
<h1 style="color:grey">Random word generator:</h1>
<button class="10letter" onclick="doAlert();" style="color:orange">Generate with 10 letters.</button>
<script>
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert() {
alert( "Your word is: "+createRandomWord(10)+" (bonus points if your word is real)." );
}
</script>
<button class="5letter" onclick="doAlert5();" style="color:orange">Generate with 5 letters.</button>
<script>
function createRandomWord5(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert5() {
alert( "Your word is: "+createRandomWord(5)+" (bonus points if your word is real)." );
}
</script>
<button class="4letter" onclick="doAlert4();" style="color:orange">Generate with 4 letters.</button>
<script>
function createRandomWord4(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz♀☺☻ƒ=ù"?',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert4() {
alert( "Your word is: "+createRandomWord(4)+" (bonus points if your word is real)." );
}
</script>
<button class="3letter" onclick="doAlert3();" style="color:orange">Generate with 3 letters.</button>
<script>
function createRandomWord3(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert3() {
alert( "Your word is: "+createRandomWord(3)+" (bonus points if your word is real)." );
}
</script>
<h1 style="color:grey">Name Generator:</h1>
<button style="color:orange" onclick="generator();">Generate</button>
<script>
function generator(){
var first = ["Kick","Stupid","Random Name","Officer","School-Related","Unoriginal","Original","Mousey","Website to name things?","n00b","Error","var first=name.first","Bob","Joe","Boris","Duck","Cheese","Pablo","Stimuli","Last Test Grade","First Word","Puss","Cat","Cherokee", "Jerry", "[Insert Weird First Name Here]"]
var last = ["Me","Idiot","dummy.dummy","randomwordgen.net16.net (shameless advertising)","he went that way","it was him!","DESTRUCTION...","Rats","You need advice for a name, use a website or something! Oh wait.","Opposition","Apple","404 not found","var last=name.last","You sure you want to pick this name?","McGuire","Rox","Knox","Bobert","Green","Raul","Damend","Milk","Positive","Negative","Rocky","Boots","Cherry","Parakeet","[Insert Weird Last Name Here]"]
var randomNumber1 = parseInt(Math.random() * first.length);
var randomNumber2 = parseInt(Math.random() * last.length);
var name = first[randomNumber1] + " " + last[randomNumber2];
alert(name);
}
</script>
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
</body>
</html>
And this is the code for the list part:
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
Thanks in advance!
Here is an example in which we take the input value, add it to an array, shuffle the array and then put it in a list <ul>. Every added value is added to the array and re-shuffles the list.
Try this:
EDIT
I added the shuffle function for when you just want to shuffle without adding new values.
var randomList = [];
function appendToArray() {
var word = document.getElementById("Words").value;
randomList.push(word);
updateList(randomList);
document.getElementById("Words").value = "";
}
function updateList(wordsArr) {
shuffleArr(wordsArr);
var list = document.getElementById('list');
list.innerHTML = "";
for (var i =0; i < wordsArr.length; i++) {
var word = wordsArr[i];
var li = document.createElement('li');
li.innerText = word;
list.appendChild(li);
}
}
function shuffleArr(arr) {
var j,
x,
i;
for (var i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
x = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = x;
}
}
function shuffleList() {
var list = randomList;
updateList(list);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Shuffle" onClick="shuffleList()">Shuffle List</button>
<h3>List</h3>
<ul id="list"></ul>
You will need to make your array variable global so you can access it from multiple functions:
// declare this only once
var arr = [];
function appendToArray() {
var word = document.getElementById("Words").value;
// check to make sure something was entered
if (word && word.length) {
arr.push(word);
// clear the input box if added to the array
document.getElementById("Words").value = '';
}
}
Then you can have another function that picks whatever you need out of the array, which is now accessible because we moved it to the global scope of your document. You could have another button to empty the array then as well.
Is this what are you looking for?
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
function showArray() {
console.log(arr);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Add" onClick="showArray()">Show List</button>
</div>
Initialize array outside the function. Otherwise you are making it empty every time you call the function.
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
</script>
</div>

struggling with creating asterisks in Javascript

I've been struggling with this for some time now. What I wanted to create is to output a triangle of asterisks based on user's input. Let say user entered size 5, it would look something like this:
*
**
***
****
*****
My HTML looks like:
<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>
<pre id="output">
</pre>
In my Javascript, I have:
function draw()
{
var size = customJS.get ( "size" ); //I have a custom library where it get the Id from HTML
var theTriangle = makeTriangle( size.value ); //sending in the size
customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}
function makeTriangle( theSize )
{
var allLines = ""; // an empty string to hold the entire triangle
for ( var i = 0; i <= size; i++) // this loop size times
{
var oneLine = createLine ( i <= size ); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine ( length )
{
var aLine = ""; // an empty string to hold the contents of this one line
for ( var j = 0; j <= i; j++ ) //this loop length times
{
aLine += '*';
}
return aLine + "<br>";
}
anyone have any tip on how I go about this? thank you so much!
Newlines in HTML normally display as spaces, but you want them to show as newlines. The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag:
customJS.set ("output", "<pre>" + theTriangle + "</pre>");
Also, you're calling createLine like this:
var oneLine = createLine ( i <= size );
i <= size yields a boolean (true or false) rather than a number. You probably mean to just pass it i:
var oneLine = createLine ( i );
Additionally, you're setting size like this:
var size = customJS.get = ( "size" );
You probably want to drop the second equals, since as is, it sets the variable size to the string "size".
And finally, you've got a few variables wrong: in makeTriangle, you're looping size times, but size is undefined; you probably meant theSize. In createLine, you're looping i times, but i is undefined; you probably meant length.
With all that, it works.
There were several bugs in your code. For example using theSize instead size as parameter in the function makeTriangle(), using i instead of length in the createLine() function in the for loop condition.
Another one was:
use
return aLine + "<br/>";
instead of
return aLine + "\n";
The working solution for your code can be found in this jsFiddle: http://jsfiddle.net/uwe_guenther/wavDH/
And below is a copy of the fiddle:
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Size:
<input type="text" id="sizeTextField">
<input id='drawButton' type="button" value="Draw">
<div id='output'></div>
</p>
<script src='main.js'></script>
</body>
</html>
main.js
(function (document) {
var drawButton = document.getElementById('drawButton'),
sizeTextField = document.getElementById('sizeTextField'),
output = document.getElementById('output');
function makeTriangle(size) {
var allLines = '';
for (var i = 0; i <= size; i++) {
var oneLine = createLine(i); // amount of asterisks for this line
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 0; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
drawButton.onclick = function () {
output.innerHTML = makeTriangle(sizeTextField.value);
};
})(document);
You can leverage some JavaScript tricks to make the code a bit more terse:
<div style="text-align: center">
<label>Size:
<input type="text" id="size" value="5">
</label> <pre id='output'></pre>
</div>
<script>
var size = document.getElementById('size'),
output = document.getElementById('output');
function update() {
var width = +size.value, // Coerce to integer.
upsideDown = width < 0, // Check if negative.
width = Math.abs(width), // Ensure positive.
treeArray = Array(width).join('0').split('0') // Create an array of 0s "width" long.
.map(function(zero, level) { // Visit each one, giving us the chance to change it.
return Array(2 + level).join('*'); // Create a string of *s.
});
upsideDown && treeArray.reverse(); // If width was negative, stand the tree on its head.
output.innerHTML = treeArray.join('\n'); // Join it all together, and output it!
}
size.onkeyup = update;
update();
size.focus();
</script>
http://jsfiddle.net/mhtKY/4/

Categories

Resources