it gives an error saying that the function "replace does not exist"
function removerPontuacao(){
let lastrow2 = sheet.getRange('AA1').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(); // código para ir para última linha
var cep = sheet.getRange("R" + lastrow2).getValue();
cep = cep.replace(/\.|\-/g, '');
sheet.getRange("R" + lastrow2).setValue(cep);
var cnpj = sheet.getRange("D" + lastrow2).getValue();
cnpj = cnpj.replace(/\/|\.|\-/g, '');
sheet.getRange("D" + lastrow2).setValue(cnpj);
}
The error you quote indicated that the value in a cell is not a text string but a number, date or Boolean that lacks the .replace() method.
To make it work, get text strings in the format displayed in the spreadsheet with .getDisplayValue(), like this:
let cep = sheet.getRange('R' + lastrow2).getDisplayValue();
// ...
let cnpj = sheet.getRange('D' + lastrow2).getDisplayValue();
Related
I want to highlight in a text all the occurrences from a word that I have in my URL.
For the first occurrence everything works fine. But I don't know how to go to the next one.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(searchText, "<mark>" + searchText + "</mark>");
el.innerHTML = marked;
}
}
I have tried to add a while(window.find(searchText) before the if but it doesn't work, it seems to loop only on the first occurence of my word.
Thanks in advance
If you're not using regex then it'll only replace the first occurrence, you might try this, Also modify the regex as per your needs.
highlightText: function(urlParams) {
var urlSearch = window.location.search;
var urlParams = new URLSearchParams(urlSearch);
var searchText = urlParams.get('search');
if (window.find(searchText)) {
var el = document.getElementById('collection-content');
text = el.innerHTML;
marked = text.replace(
RegExp(`(${searchText})`),
"<mark>" + searchText + " </mark>");
el.innerHTML = marked;
}
}
Note: The match is case sensitive
So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)
I don't know how to solve this. I created a java method which create a String with all the information in the language of the local :
public String getAllCountries(){
StringBuilder sb = new StringBuilder();
sb.append("[ ");
ResourceBundle bundlePays = ResourceBundle.getBundle(BUNDLE_PAYS, localeBean.getLocale());
for(int i = 0; i< bundlePays.keySet().size(); i++ ){
String key = (String) bundlePays.keySet().toArray()[i];
String nomPays = traduirePays(key);
ResourceBundle bundlePrefix = ResourceBundle.getBundle(BUNDLE_PREFIX);
if ((AieStringUtils.getSafeBundleString(bundlePrefix, key)) != key){
String prefix = bundlePrefix.getString(key);
sb.append("[");
sb.append("\"" + nomPays + "\"" + "," + "\""+ key +"\"" + "," + "\""+ prefix + "\"");
if (i!=bundlePays.keySet().size()-1){
sb.append("], ");
}else{
sb.append("] ");
}
}
}
sb.append(" ]");
String allCountries = sb.toString();
System.out.println(allCountries);
return allCountries;
}
I put the result in my xhtml like this :
<inputTextArea type="hidden" name="allCountries" id="allCountries"
value="#{pageInfoPerso.allCountries}"/>
It gives me this kind of result :
[ ["Vanuatu","VU","678"], ["Vietnam","VN","84"], ["Equateur","EC","593"], ["Iles Vierges Americaines","VI","1"], ["Algerie","DZ","213"], ["Iles Vierges Britanniques","VG","1"], ["Venezuela","VE","58"] ]
etc
Then, I want to use this in intlTelInput.js
So, I decided to put the var inside the js and to insert it that way from the xhtml :
<h:outputScript>
jQuery(document).ready(function() {
$("#phoneNumber").intlTelInput({
var allCountries={allCountries : document.getElementById("allCountries").innerHTML};
utilsScript: "/js/utils.js"
});
$("#phoneNumber2").intlTelInput({
utilsScript: "/js/utils.js"
});
});
</h:outputScript>
It's not working and I get this error :
"SyntaxError: missing : after property id"
I have to probably tell you at this point that I never do any front and never touched Javascript before :/
I also tried directly in
the js file to put my var like this at the top of it :
//var allCountries = document.getElementById("allCountries").innerHTML;
//
//for (var i = 0; i < allCountries.length; i++) {
// var c = allCountries[i];
// allCountries[i] = {
// name: c[0],
// iso2: c[1],
// dialCode: c[2],
// priority: c[3] || 0,
// areaCodes: c[4] || null
// };
//}
It didn't work either and I got this message :
"this.countries[0] is undefined intl tel input "
Can somebody explain to me how I can pass my String from java to html to Js please ?
Thank you so much in advance. It's been two days I'm searching, I'm going crazy.
I'm quite annoyed by a problem with google script and javascript.
I have a problem to send datarange values from my google script to be treated by my javascript function.
Here is my code.
code.gs extract:
function getSheetData(ss,sh){
// Create sheet object
var ass = SpreadsheetApp.openById(ss);
SpreadsheetApp.setActiveSpreadsheet(ass);
var ash = SpreadsheetApp.openById(ss).getSheetByName(sh);
ash = SpreadsheetApp.getActive();
var result = ash.getDataRange().getValues();
Logger.log("getSheetData(ss,sh) result : "+result);
// return result after JSON strinfigy
return JSON.stringify(result);
}
JavaScript.html extract :
function readTb(fn) {
var result = google.script.run.getSheetData(bdData, tbData);
console.dir('readTb result : ' + result);
fn(result);
}
function buildSelect(range) {
console.log('Range = ');
console.dir(range);
if (range.length > 0) {
buildOption('', 'Choose an order');
for (i = 0; i < range.length; i++) {
var row = range[i];
buildOption(row[0], row[0] + " ~ " + row[2] + " ~ " + row[5]
+ " ~ " + row[7]);
}
} else {
buildOption('', 'No order to display');
}
}
function buildOption(data) {
console.log(data);
}
/**
/* Retrieve orders and format to fill select numCommande input
/*
*/
function listCommandesPesee() {
console.log('Call for orders seeking');
// Read DB and retrieve data
// feed function variables with CONST
bdData = BDDATA_OLD;
tbData = TBCOMMANDES;
// Call readTb to retrieve data, then buildSelect to format result
var promise1 = new Promise(readTb);
promise1.then(buildSelect);
console.dir(promise1);
}
By now, Logger.log in GS IDE shows right data:
[16-07-27 08:01:22:040 PDT] résultat de getSheetData(ss,sh) : Ligne,ID,Produit,Date,Fournisseur,Numéro Camion,Silo,Cellule,Ilot,Poids coop,Poids net livré,N° analyse qualité,Cellule destination ,Transport
...
on page load, listCommandesPesee is called, which call readTb().
But even with json stringify, I still have an undefined value in var result (readTb function) and so range in buildSelect doesn't have any length property.
JSON.Stringify was working when I was testing and before I add promise and chain (I do think)
Because I'm stuck on this. I'll be grateful for any help.
Thanks
The return from the server, can not be received by the same function that is using google.script.run.
Currently:
function readTb(fn) {
var result = google.script.run.getSheetData(bdData, tbData);
console.dir('Résultat de lecture des données : ' + result);
fn(result);
}
Should Be:
function readTb() {
var result = google.script.run
.withSuccessHandler(mySuccessFnc)
.getSheetData(bdData, tbData);
}
function mySuccessFnc(resultReturned) {
console.dir('Résultat de lecture des données : ' + resultReturned);
};
I have been struggling with a script I have been working on for a while. The problem is that when I run the script with text like:
Hi. apples are amazing.
I want to make only the a in apples capitalized, but instead the text comes out as:
Hi. Apples Are Amazing.
Here is the code:
function caps()
{
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText()
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lower = "abcdefghijklmnopqrstuvwxyx";
//while (() != null) {
//var search = text.findText('. a')
//var start = replace - 1
//text.deleteText(start, replace)
//text.insertText(start, " A")//}
for(var i=0; i<caps.length; i++)
{
var nextCaps = caps.charAt(i);
var nextLower = lower.charAt(i);
while (text.findText('. ' + nextLower) != null)
{
Logger.log(nextLower)
Logger.log(nextCaps)
var search = text.findText('. ' + nextLower)
var replace = search.getEndOffsetInclusive()
var start = replace - 1
text.deleteText(start, replace)
text.insertText(start, " " + nextCaps)
}
//var nextChar = caps.charAt(i);
//Logger.log(nextLower)
}
}
Basically, the code looks for ". a" and replaces it with ". A" (same with b, c, d and so on). If anyone can help me with this it would be very much appreciated.
The below code follows your example where you want to capitalize the first letter after the end of the first sentence. So long as that is the case this regex and replace will do that for any letters.
var str = 'Hi. apples are amazing.';
var reg = /\.\s./;
function replacement(match) {
return match.toUpperCase();
}
str = str.replace(reg, replacement);
Logger.log(str);