I have this string -
ContactTrigger: execution of AfterInsert
caused by: System.DmlException: Update failed. First exception on row 0 with id 0032200000AYK5AAAX; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Spouse Cannot be more than 1: []
Class.ContactTriggerHelper.updateDependentData: line 309, column 1
Trigger.ContactTrigger: line 26, column 1
I need to identify if this string contains FIELD_CUSTOM_VALIDATION_EXCEPTION and I need to extract this part of the message 'Spouse Cannot be more than 1'
Which I am not able to
I tried this --
var pageErrors = saveResult.error[0].pageErrors[0].message;
console.log('pageErrors--->'+pageErrors);
var errMessage;
if(pageErrors.includes('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
console.log('Inside includes');
console.log('pageErrors.indexOf("FIELD_CUSTOM_VALIDATION_EXCEPTION")-->'+pageErrors.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION'));
console.log('pageErrors.lastIndexOf("FIELD_CUSTOM_VALIDATION_EXCEPTION")-->'+pageErrors.lastIndexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION,'));
errMessage = pageErrors.substring(pageErrors.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION'),pageErrors.lastIndexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION,'));
}
You can try this
FIELD_CUSTOM_VALIDATION_EXCEPTION,\s*([^:]+)
let findValue = (str) => {
return str.match(/FIELD_CUSTOM_VALIDATION_EXCEPTION,\s*([^:]+)/i)
}
let str = `ContactTrigger: execution of AfterInsert
caused by: System.DmlException: Update failed. First exception on row 0 with id 0032200000AYK5AAAX; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Spouse Cannot be more than 1: []
Class.ContactTriggerHelper.updateDependentData: line 309, column 1 Trigger.ContactTrigger: line 26, column 1`
console.log(findValue(str))
console.log(findValue(str)[1])
let str2 = `ContactTrigger: execution of AfterInsert
caused by: System.DmlException: Update failed. First exception on row 0 with id 0032200000AYK5AAAX;
Class.ContactTriggerHelper.updateDependentData: line 309, column 1 Trigger.ContactTrigger: line 26, column 1`
console.log(findValue(str2))
You can even do something simpler and faster than regular expressions. Since you know the exact error message you need to track, you can split the error string from end of the error massage up to end of line or up to ":" character (you can also optionally trim it if you need to remove any surrounding spaces).
So:
const str = `ContactTrigger: execution of AfterInsert
caused by: System.DmlException: Update failed. First exception on row 0 with id 0032200000AYK5AAAX; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Spouse Cannot be more than 1: []
Class.ContactTriggerHelper.updateDependentData: line 309, column 1 Trigger.ContactTrigger: line 26, column 1`;
const ERR = 'FIELD_CUSTOM_VALIDATION_EXCEPTION,';
const ind = str.indexOf(ERR);
let msg = -1 < ind ? str.slice(ind+ERR.length, str.indexOf("\n",ind+ERR.length)) : null;
msg = msg ? msg.trim() : null; // optionally trim it as well
console.log(str);
console.log(msg);
Related
I am trying to make a simple encoder in javascript, and copying the output to the clipboard, but the code gives an error.
I tried this code:
function encode() {
let alphabet = " abcdefghijklmnopqrstuvwxyz1234567890-=!##$%^&*()_+[];'/.,'{}|:~";
const a_list = alphabet.split('');
const m_list = prompt("message: ").split('');
let return_message = "";
for (let i = 0; i < m_list.length; i++) {
let current_letter = m_list[i];
let translated_letter = a_list[a_list.indexOf(current_letter) + 5];
return_message += translated_letter;
}
navigator.clipboard.writeText(return_message);
}
encode()
but the console gives this error:
Error: DOMException {INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, …}
I host the server in replit.
When I try to do an alert with the encoded words, it works fine.
navigator.clipboard.writeText requires a transient user activation. That is why it works when you click on an alert box.
Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.
The "clipboard-write" permission of the Permissions API is granted automatically to pages when they are in the active tab.
https://devdocs.io/dom/clipboard/writetext
The error you are getting is because the indexOf function returns -1 when the sought character is not found in the a_list array.
You can check whether the index returned by indexOf is greater than or equal to zero before accessing the element in the a_list array. If the index returned is less than zero, you can simply add the original character to return_message.
Here is an example:
function encode() {
// Define the list of characters to be substituted
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const charList = alphabet.split('');
// Receive the string to be substituted from the user
const inputString = prompt("Enter the string to be substituted:");
// Convert the string to an array of characters
const inputChars = inputString.split('');
// Create a new array with the substituted characters
const outputChars = inputChars.map(char => {
// Find the index of the current character in the character list
const index = charList.indexOf(char.toLowerCase());
// If the character is not in the character list, keep the original character
if (index === -1) {
return char;
}
// Find the next character in the character list
const nextIndex = (index + 1) % charList.length;
const nextChar = charList[nextIndex];
// Return the next substituted character
return char.toUpperCase() === char ? nextChar.toUpperCase() : nextChar;
});
// Convert the array of characters back to a string
const outputString = outputChars.join('');
// Display the substituted string in the console
navigator.clipboard.writeText(outputString);
}
encode()
And as answered in #dotnetCarpenter reply navigator.clipboard.writeText requires a transient user activation. That's why it works when an alert box is clicked.
I have a String message like that :
messages = "Line 249 : Validation error, Line 287 : Validation error"
I want to split this message like this :
messages [] = [ { position: 1, message: 'Line 249 : Validation error' },
{ position: 2, message: 'Line 287 : Validation error' }]
Could you please help with this thank you.
The easiest way to turn a string into an array of objects is to first split the string using the delimiter, which in this case is the comma, so start with.
const test = "Line 249 : Validation error, Line 287 : Validation error";
const parts = test.split(",");
Then, you want to use the map array function to return an object for each part that's been split. The es6 map function has a callback that returns the piece of the array and the index in which it was found. you don't want the index, but rather an ordinal (per your example above)
Here's what i would do:
const test = "Line 249 : Validation error, Line 287 : Validation error";
const parts = test.split(",").map((text, index) => {
return {
position: index+1,
message: text.trim()
}
});
Now, the parts variable holds an array of objects that matches your required output
I think your error message can be split into an array using javascript split method.
so
messages = message.split(',')
will do the magic
But to add your position,
let messages = "Line 249 : Validation error, Line 287 : Validation error"
messages= messages.split(',').map((x,index)=>{
let obj ={}
obj.position=index+1;
obj.message = x
return obj;
});
console.log( messages )
I am trying to split this string down into sections:
2 h 3 12 s
From this I am trying to create a longer string such as:
00020312
DDHHMMSS
I am getting an error on line 21:
Cannot read property split of undefined
//calculate which ticket is the oldest begining
jQuery('.table-list-search tr').each(function(){
var downTime = jQuery(this).find('.downTime').text();
downTime = String(downTime);
var hasDays = downTime.split("d");
var hasHours = downTime.split("h");
var hasMins = downTime.split("m");
var hasSeconds = downTime.split("s");
if(hasDays[1] === undefined){
var downTimeD = downTime.split(" d")[0];
downTime = downTime.split(" d ")[1];
if(downTimeD <=9){
downTimeD = downTimeD.toString(downTimeD);
downTimeD = '0' + downTimeD;
};
}else{
var downTimeD = '00';
};
if(hasHours[1] === undefined){
var downTimeH = downTime.split(" h")[0];
downTime = downTime.split(" h ")[1];
if(downTimeH <=9){
downTimeH = downTimeH.toString(downTimeD);
downTimeH = '0' + downTimeH;
};
}
Your task can be done by applying a regular expression:
const rx=/(?:(\d+) *d *)?(?:(\d+) *h *)?(?:(\d+) *m *)?(?:(\d+) *s *)?/;
const fmt=s=>(s||'0').padStart(2,'0');
console.log('DDHHMMSS')
console.log( rx.exec('2 h 3 m 12 s').slice(1).map(fmt).join('') )
console.log( rx.exec('1d24m' ).slice(1).map(fmt).join('') )
The expression looks for (optional) groups of numbers with the letters 'd', 'h', 'm' or 's' behind them, qualifying each number in turn as "days", "hours", "minutes" and "seconds".
Debuggex Demo
The result is returned as an array. From this array only the elements 1 to 4 being used, as the 0-th element would be the complete matched string.
The whole job can also be packed into a single function like:
fmta=dt=>/(?:(\d+) *d *)?(?:(\d+) *h *)?(?:(\d+) *m *)?(?:(\d+) *s *)?/
.exec(dt).slice(1).map(s=>(s||'0').padStart(2,'0')).join('');
console.log(fmta('12d6h56m 45s')); // '12065645'
Where does downTime come from? The error you're getting means that the variable does not exist. It might be a typo somewhere.
Edit - this was posted before the question contained a full code snippet, but the answer stands - if you get such an error, it usually is because the variable is not defined.
Edit 2 - There are a number of weird things in the logic. First if(hasDays[1] === undefined) essentially translates to "downTime has no 'd' in it", so all further attempts to break on 'd' do not split the string. So downTime = downTime.split(" d ")[1]; would never yield anything - downTime has no d's, so it can't be split on them.
Then there' a corner case in the line downTime = downTime.split(" d ")[1]; (and the similar one below). You're splitting on " d "while the above splits are on " d" and "d".
In summary, you would like to change if(hasDays[1] === undefined) to if(hasDays[1] !== undefined) and always split on "d" with no extra spaces, and the same for the things below.
Based on https://www.plivo.com/blog/Send-templatized-SMS-from-a-Google-spreadsheet-using-Plivo-SMS-API/ I have the following code:
function createMessage(){
data = {
"SOURCE" : "+1234567890",
"DESTINATION" : "+2345678901",
"FIRST_NAME" : "Jane",
"LAST_NAME" : "Doe",
"COUPON" : "DUMMY20",
"STORE" : "PLIVO",
"DISCOUNT" : "20",
}
template_data = "Hi , your coupon code for discount of % purchase at is "
Logger.log(data);
for (var key in data) {
Logger.log(key);
if (data.hasOwnProperty(key)) {
template_data = template_data.replace(new RegExp('+key+', 'gi'),data[key]); // error here
}
}
Logger.log(template_data);
return template_data;
}
When I run createMessage I get :
SyntaxError: Invalid quantifier +. (line 57, file "Code")
From a previous question and if I understand correctly the loop goes through each key, value pair looking for all matches of the key (g) in a case insensitive fashion (i).
I don't understand the pattern '+key+' This causes the error and my attempts to test patterns like '+SOURCE+' also give the same error, although the seem to work while testing at https://regex101.com/r/CF967t/2 .
Can someone give me an explanation of the problem
sign + usually is a repetition operator, and causes the preceding token to repeat one or more times key+ would be expressed as keykey*
You have pass only key
template_data = template_data.replace(new RegExp(key, 'gi'),data[key]);
I've done this in JavaScript but needless to say I can't just swap it over.
In Jscript I used this:
var estr = tx_val
index = 0
positions = []
while((index = estr.indexOf("e", index + 1)) != -1)
{
positions.push(index);
}
document.getElementById('ans6').innerHTML = "Locations of 'e' in string the are: "
+ positions;
I tried using the same logic with VBS terms, ie join, I also tried using InStr. I'm just not sure how to yank out that 'e'... Maybe I'll try replacing it with another character.
Here is what I tried with VBScript. I tried using InStr and replace to yank out the first occurance of 'e' in each loop and replace it with an 'x'. I thought that maybe this would make the next loop through give the location of the next 'e'. -- When I don't get a subscript out of range 'i' error, I only get one location back from the script and its 0.
(6) show the location of each occurence of the character "e" in the string "tx_val" in the span block with id="ans6"
countArr = array()
countArr = split(tx_val)
estr = tx_val
outhtml = ""
positions = array()
i=0
for each word in countArr
i= i+1
positions(i) = InStr(1,estr,"e",1)
estr = replace(estr,"e","x",1,1)
next
document.getElementById("ans6").innerHTML = "E is located at: " & positions
What can I do that is simpler than this and works? and thank you in advance, you all help a lot.
EDIT AGAIN: I finally got it working right. I'm not 100% how. But I ran through the logic in my head a few dozen times before I wrote it and after a few kinks it works.
local = ""
simon = tx_val
place=(InStr(1,simon,"e"))
i=(len(simon))
count = tx_val
do
local = (local & " " & (InStr((place),simon,"e")))
place = InStr((place+1),simon,"e")
count = (InStr(1,simon,"e"))
loop while place <> 0
document.getElementById("ans6").innerHTML= local
InStr has slightly different parameters to indexOf:
InStr([start, ]string, searchValue[, compare])
start: The index at which to start searching
string: The string to search
searchValue: The string to search for
Also note that Visual Basic indexes strings beginning at 1 so all the input and return index values are 1 more than the original JavaScript.
You can try split(). For example a simple string like this:
string = "thisismystring"
Split on "s", so we have
mystring = Split(string,"s")
So in the array mystring, we have
thi i my tring
^ ^ ^ ^
[0] [1] [2] [3]
All you have to do is check the length of each array item using Len(). For example, item 0 has length of 3 (thi), so the "s" is at position 4 (which is index 3). Take note of this length, and do for the next item. Item 1 has length of 1, so we add it to 4, to get 5, and so on.
#Update, here's an example using vbscript
thestring = "thisismystring"
delimiter="str"
mystring = Split(thestring,delimiter)
c=0
For i=0 To UBound(mystring)-1
c = c + Len(mystring(i)) + Len(delimiter)
WScript.Echo "index of s: " & c - Len(delimiter)
Next
Trial:
C:\test> cscript //nologo test.vbs
index of str is: 8