I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);
I want to limit how long a string is when updated by JS. To do so, I want to use a loop that checks the length of the current string and only accepts new inputs if the string is shorter than the maximum length.
For some reason when I ask for the length of the html element, it returns the... nature of the element?
This specifically: [object HTMLParagraphElement]
This is how I'm getting the html element:
const digits = document.getElementById("digits");
This is how I'm trying to limit the size, I marked which line I'm currently using to add numbers (it works on its own, I just want to limit how long the string can be):
addEventListenerList(numeral, "click", () => {
if (digits.toString().length > 10){ //(*)
return null;
} else {
digits.innerText += event.target.value; //This is the line that adds numbers.
}
});
So yeah, it's not working because line (*) is finding the current length to be 29 (the length of [object HTMLParagraphElement]). I have no idea how to get the length of the content, and not this... what is this exactly?
I don't know if it's useful, but just in case, numeral is a node list that I iterate through using this:
function addEventListenerList(list, event, fn){
for (let i = 0, len = list.length; i < len; i++) {
list[i].addEventListener(event, fn);
}
}
The most direct way to solve this is to use digits.textContent.length > 10 instead of digits.toString(). However, as others have noted, digits.value.length and/or digits.innerHTML.length may be relevant in some cases.
innerHTML is less desirable here because nested html objects or formatting tags like or will count as part of the calculated length. It also uses more memory than .textContent. See innerText vs innerHtml vs label vs text vs textContent vs outerText for a longer discussion on the differences.
You assigned the element to variable not its contents, to get the length of the contents depends on what element type it is.
If it is a input then you can get the value:
digits.value.length
If it is another type you can use the innerHTML property:
digits.innerHTML.length
I have a WooCommerce store, which is connected with Zapier to a Google spreadsheet. In this file, I keep track of the sales etc. Some of these columns contain -obviously- prices, such as price ex VAT, etc. However, for some reason the pricing values are stored in my spreadsheet as strings, such as 18.21.
To be able to automatically calculate with these values, I need to convert values in these specific columns to numbers with a comma as divider. I'm new to Google Script, but with reading some other post etc, I managed to "write" the following script, which almost does the job:
function stringIntoNumber() {
var sheetActive = SpreadsheetApp.openById("SOME_ID");
var sheet = sheetActive.getSheetByName("SOME_SHEETNAME");
var range = sheet.getRange("R2:R");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(".", ",")];
}));
}
The script works fine as long as only values with a dot can be found in column R. When values that belong to the range are changed to values with a comma, the script gives the error:
TypeError, can't find the function Replace.
Select the column you want to change.
Goto Edit>Find and Replace
In Find area put "."
in Replace with area put ","
The error occurs because .replace is a string method and can't be applied to numbers. A simple workaround would be to ensure the argument is always a string, there is a .toString() method for that.
in your code try
return [row[0].toString().replace(".", ",")];
The locale of your spreadsheet is set to a country that uses commas to seperate decimal places. Zapier however seems to use dots and therefore google sheets interprets the data it gets from Zapier as strings since it can't interpret it as valid numbers.
If you change the locale to United States (under File/Spreadsheet settings) it should work correctly. But you may not want to do that because it can cause other issues.
You got a TypeError because the type was number and not string. You can use an if statement to check the type before calling replace. Also you should convert the type to 'number' to make sure it will work correctly independent of your locale setting.
range.setValues(range.getValues().map(function(row) {
if(typeof row[0] === "string") return [Number(row[0].replace(",", "."))];
else return row;
}));
In this case I convert , to . instead of the other way around since the conversion to number requires a ..
Click on Tools > Script Editor.
Put this on your macros.gs (create one if you don't have any):
/** #OnlyCurrentDoc */
function ReplaceCommaToDot() {
var range = SpreadsheetApp.getActiveRange();
var col = range.getColumn();
var row = range.getRow();
function format(str) {
if(str.length == 0) return str;
return str.match(/[0-9.,]+/)[0]
.replace('.','')
.replace(',','.');
}
var log = [range.getRow(), range.getColumn()];
Logger.log(log);
var values = range.getValues()
for(var row = 0; row < range.getNumRows(); row++){
for(var col = 0; col < range.getNumColumns(); col++){
values[row][col] = format(values[row][col]);
}
}
range.setValues(values);
}
Save. Go back to the spreadsheet, import this macro.
Once the macro is imported, just select the desired range, click on Tools > Macro and select ReplaceCommaToDot
Note: This script removes the original ., and replaces , by .. Ideal if you are converting from US$ 9.999,99 to 9999.99. Comma , and whatever other text, like the currency symbol US$, were removed since Google Spreadsheet handles it with text formatting. Alternatively one could swap . and ,, like from US$ 9.999,99 to 9,999.99 by using the following code snippet instead:
return str.match(/[0-9.,]+/)[0]
.replace('.','_')
.replace(',','.')
.replace('_',',');
An alternative way to replace . with , is to use regex functions and conversion functions in the Sheets cells. Suppose your number is in A1 cell, you can write this function in any new cell:
= IF(REGEXMATCH(TO_TEXT(A1), "."), VALUE(REGEXREPLACE(TO_TEXT(A1), ".", ",")), VALUE(A1))
These functions do the following step:
Convert the number in the target cell to text. This should be done because REGEXMATCH expects a text as its argument.
Check if there is a . in the target cell.
If there is a ., replace it with ,, and then convert the result to a number.
If there is no ., keep the text in the target cell as is, but convert it to a number.
(Note : the Google Sheets locale setting I used in applying these functions is United States)
I have different solution.
In my case, I`m getting values from Google Forms and there it is allowed use only numbers with dot as I know. In this case when I capture data from Form and trigger script which is triggered when the form is submited. Than data is placed in specific sheet in a specific cell, but formula in sheet is not calculating, because with my locale settings calculating is possible only with a comma not dot, that is coming from Google Form.
Then I use Number() to convert it to a number even if it is already set as a number in Google Forms. In this case, Google Sheets script is converting number one more time to number, but changes dot to comma because it is checking my locale.
var size = Number(sizeValueFromForm);
I have not tested this with different locale, so I can`t guarantee that will work for locale where situation is opposite to mine.
I hope this helps someone. I was looking for solution here, but remembered that some time ago I had similar problem, and tried this time too and it works.
=IF(REGEXMATCH(TO_TEXT(F24);"[.]");REGEXREPLACE(F24;"[.]";",");VALUE(F24))
Works for me
If find dot replace with comma if not, put value
I have several paths I've made in D3.JS and on mouseover I call this mouseover function to get the attributes of that path and store them in variables. Then I try to measure the length of the level attribute and console.log it, however Im getting an error:
I'd also like to use the .slice(-1,1) method to get the last figure in that value attribute but this doesn't work either.
I think the attribute needs to be read as a string in order to do these things. but when I call .toString() on circleLevel I'm still getting this error.
here is the mouseover function:
function mouseover(){
var circleName = d3.select(this).attr("name");
var circleSize = d3.select(this).attr("size");
var circleLevel = d3.select(this).attr("level");
var levelLength = circleLevel.length();
console.log(circleLevel.length());
}
here it is on JS fiddle: http://jsfiddle.net/RL_NewtoJS/ryyt6ruj/3/
In JavaScript, string length is a prop, not a method. So
circleLevel.length()
should be
circleLevel.length
The error is because it's trying to call the length, the Number, as a function: 5() // invalid
Regarding obtaining the last character, either use
circleLevel.charAt(circleLevel.length - 1)
or
circleLevel.substr(circleLevel.length - n) // to get last n characters
This should be pretty simple. I'm trying to use the slice method to remove the last two characters in a dynamically created string in a shopping cart.
So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.
I've created a JSFiddle here:
http://jsfiddle.net/EbckS/
The jQuery that's not working is below:
$(".myclass").slice(0,-2);
You should use text.
$(".slice").text(function(i, text) {
return text.slice(0, -2);
});
i Reffers the index position of the element in the set
text Reffers the old text value
Refference
Very Simple. I uses this for getting number from a string you can use it too.
var height= "800px";
var newheight = height.substring(0,height.length-2); //string 800
newheight= parseFloat(newheight) || 0; //number 800