Delete empty Spaces in String Array (JavaScript) - javascript

I have the following Array in JavaScript:
["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"]
I would like to delete the empty spaces before a letter is beginning, see for example X2. But I would like that the space between X and YZ1 is not deleted.
Does anybody know, how I can do that?
Thank you in advance.
Greets.

RegEx to replace leading whitespace:
for (var i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(/^\s+/, "");

You can try, replace()
strArray[0].replace(/\s/g, "") ;

for (var i = 0; i < array.length; i++)
array[i] = array[i].trim();
}

here is working solution, that adds a new method to Array object.
Demo: http://jsfiddle.net/bnpeon25/
a = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
Array.prototype.trimvals = function() {
for (var i = 0; i < this.length; i++) {
this[i] = this[i].replace(/^\s+/, "");
}
return this;
}
console.log(a.trimvals());

All modern browsers natively support .trim(). Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
arr[i] = arr[i].trim();
This will not delete the embedded spaces as you stated in your question.
Alternatively, if you want to get rid of all spaces: leading, trailing and embedded; then you could you regex:
arr[i] = arr[i].replace(/\s/g, "");
Snippet using .trim() (Leading and Trailing Spaces):
var arr = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].trim(); }
document.getElementById("result").innerText = arr.join(",");
<p id="result"></p>
Snippet using regex (Simple all spaces):
var arr = ["X1", " X2", " X3", " X4", " X5", " X6", " X YZ1", " X YZ2", " X7", " X8", " X9"];
for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].replace(/\s/g, ""); }
document.getElementById("result").innerText = arr.join(",");
<p id="result"></p>

Related

How to use the splice and binary search on the data to delete and search

I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}

How do I fix this code regarding getelementbyid [Javascript]?

So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

How do i stop my array info from printing twice?

I have an array of objects
var event1Array {
name: wedding;
time: ["10:00am", "12:00pm"];
}
var event2Array {
name: housewarming;
time: ["7:00pm", "9:00pm"]
}
var eventArray = [event1Array, event2Array];
I want to loop through using just two loops (inner and outer) using an alert like this
alert("attend a " + eventArray.name + " starting " + theEvent.time)
But my event info keeps printing twice like
attend a wedding starting 10am,
attend a wedding starting 12pm
attend a housewarming starting 7pm
attend a housewarming starting 9pm
here's the complete code
var event1Array
{
name: wedding;
time: ["10:00am", "12:00pm"];
}
var event2Array
{
name: housewarming;
time: ["7:00pm", "9:00pm"];
}
var div = document.getElementById("events");
var eventArray = [event1Array, event2Array];
for (var i = 0; i < eventArray.length; i++)
{
var theEvent = eventArray[i];
for (j = 0; j < theEvent.time.length; j++)
{
console.log("Attending a wedding" + theEvent.name + "starting" + theEvent.time[j]);
}
}
They aren't Arrays. event1Array and event2Array are actually Objects, so you don't want to loop through them. You should only be looping through the eventArray.
for (var i = 0, len = eventArray.length; i < len; i++) {
alert("attend a " + eventArray[i].name + " starting " + eventArray[i].time[0]);
}
Here is a working jsfiddle...
try this
alert("attend a " + eventArray.name + " starting " + theEvent.time[0])

how to remove a comma and replace with a period javascript

I have a string that I have created where I would like to remove the last comma and replace it with a period. I want to keep all of the other commas. Here I was trying to use a conditional statement, it works to add commas, but it doesn't work to replace the last one with a period. I am new at this, I would really appreciate any help.
for (var i = 0; i < petArray.length; i++) {
petObj = petArray[i];
likesString = petObj.name + " " + " is a " + petObj.type + " she " + " likes ";
for (var j = 0; j < petObj.likes.length; j++) {
if (j < petObj.likes.length) {
var likesString = likesString + petObj.likes[j] + ", ";
}
else if (j == petObj.likes.length) {
likesString.replace(", ", ".");
}
}
displayResult();
}
You seem to be doing it a hard way! Use the Arry's join() method to build the list.
for (var i = 0; i < petArray.length; i++) {
petObj = petArray[i];
likesString = petObj.name + " is a " + petObj.type + " she likes " +
petObj.likes.join(", ") + ".";
displayResult();
}
This will do it:
str.replace(/,([^,]*)$/,".$1")
The regular expression matches on a comma followed by any number of non-commas all the way to the end of the string... by definition, this is the last comma. It works if there are no commas, one comma or any number of commas.
Notice that the 'if' part of this has to always be true so the 'else' part is never executed:
for (var j = 0; j < petObj.likes.length; j++) {
if (j < petObj.likes.length) {
var likesString = likesString + petObj.likes[j] + ", ";
}
else if (j == petObj.likes.length) {
likesString.replace(", ", ".");
}
}
The for loop says to only continue if that condition is true and your code then tests the same condition.
You might just do something like this:
for (var j = 0; j < petObj.likes.length; j++) {
if (j < petObj.likes.length-1) {
likesString = likesString + petObj.likes[j] + ", ";
}
else {
likesString = likesString + petObj.likes[j] + ". ";
}
}
There are better ways to do the condition that don't duplicate so much but that might do what you want. (Also I fixed the extra 'var' part.)
Here is a great place to learn and test regular expressions: RegExr
Essentially, you want to replace the following:
RegExp Pattern: /,([^,]+)$/
Replace Pattern: .$1
So your code should look like:
s.replace(/,([^,]+)$/, '.$1');
Where s is the string you're trying to replace the last comma in.
Don't forget to set that line to a variable to save it.
To replace the last occurrence of a comma in a string with a period, you can use:
var index = str.lastIndexOf(",");
var newstr = str.substring(0, index) + "." + str.substring(index + 1);
After looking at your code, it seems epascarello's approach is the best. In addition to what he has pointed out, if there are no elements in the array, your string will somewhat abruptly end with: "she likes". To fix this, you could use:
likesString = petObj.name + " is a " + petObj.type + (petObj.likes.length ? ", she likes " + petObj.likes.join(", ") : "") + ".";
For start you can avoid to put the last comma with a code like this:
for (var i = 0; i < petArray.length; i++) {
petObj = petArray[i];
var likesString = petObj.name + " " + " is a " + petObj.type;
if (petObj.likes.length) {
likesString = likesString + " she " + " likes " petObj.likes.join(", ");
}
likesString = likesString + '.'
displayResult();
}
If you still want to use your code you have to test versus lenght-1 as the likes array indexes go from 0 to length-1:
for (var i = 0; i < petArray.length; i++) {
petObj = petArray[i];
var likesString = petObj.name + " " + " is a " + petObj.type + " she " + " likes ";
for (var j = 0; j < petObj.likes.length; j++) {
likesString = likesString + petObj.likes[j] + ((j == petObj.likes.length-1)?'.':', ';
}
displayResult();
}
If you still want to change the string after its construction you can just remove the last two characters
likesString=likesString.replace(/, $/,'.')
That is because replace() returns a new string with the new value instead of changing the string itself, you could do this instead:
likesString = likesString.replace(/,\s$/, ".");

Categories

Resources