how to remove a comma and replace with a period javascript - 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$/, ".");

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(){
}

Displaying times table using javascript

As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;

Function title var

I have written a code that finds two strings and in return it should tell me if these two strings are existing:
function searchTwoString(data, str1, str2) {
var strX = str1 + " " + strValueX + "\r\n";
var strY = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
var strValueX = " exist";
continue;
} else if (data[i] === str2) {
var strValueY = " exist";
break;
}
}
return strX + strY;
}
Achieved result:
str1 undefined
str2 undefined
Expected result:
str1 exist
str2 exist
it tells me my strvalueX & strvalueY are undefined isn't it i have already gave the values in the if statement?
thanks to those who will help out
Here is an answer to your question with comment.
Hope you understand what I'm talking about.
function searchTwoString(data, str1, str2) {
var strX;// = str1 + " " + strValueX + "\r\n";
var strY;// = str2 + " " + strValueY;
var strValueX;
var strValueY;
for (var i = 0; i < data.length; i++) {
if (data[i] === str1) {
// var strValueX = " exist";
// do not define again
strValueX = " exist";
continue;
} else if (data[i] === str2) {
// var strValueY = " exist";
// do not define again
strValueY = " exist";
break;
}
}
// define the value here after strValueX and strValueY is set
strX = str1 + " " + strValueX + "\r\n";
strY = str2 + " " + strValueY;
return strX + strY;
}
The order of your statements is off. In lines 2 and 3, you are using strValueX and strValueY before they are defined. Lines 2 and 3 should be moved to before the return so that they will have the updated values.
I believe there is also a shadowing problem, as in the if statements you are creating new variables with the var keyword (e.g. var strValueX = " exist";). You will want to remove var from the if statements so that it updates the values of the outer variables.

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;
}

Delete empty Spaces in String Array (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>

Categories

Resources