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 )
Related
I'm testing out my regex validator using js, I've tested the regex in tester it is valid but I think the problem is with my code, I'm fairly new to JS. Hoping someone can help me on this one. Thank you
So this is the input string that I use, then I tokenize the returned value to each string it's a valid yyyy-mm-dd format to check if it's a date.
project = "HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate <= 2022-10-31)
const items = token.split(" ");
for (const item of items) {
console.log(item.match("([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))"))
}
I don't know why it returns null, BTW I just need to capture the date so I can replace the date with whatever I want. Thank you
Just change the string "" to a regex expression //. Instead of "([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))", change it to this: /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/.
It should, for example, return the following array:
[
'2022-10-31',
'2022-10-31',
'10',
'31',
index: 0,
input: '2022-10-31)',
groups: undefined
]
Where you can access the matched value by item[0].
So the new code is as follows:
const token = `HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate <= 2022-10-31)`
const regex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
const items = token.split(" ");
for (const item of items) {
const match = item.match(regex)
if (match) console.log(match[0])
}
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);
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 have javascript function that calls an external Api and returns in most case a valid JSON string.
function (successResponse) {
{
console.log(successResponse);
}
However, in some cases it return the the following invalid JSON
Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null
How can I parse the above string to get the 'uuid'
Thanks
If you're expecting a response string in that format, you can use a regular expression to extract the "text" portion of the response:
function (successResponse) {
{
var responseText = successResponse.match(/\{.+\}/);
var responseTextJSON = JSON.parse(responseText);
var uuid = responseTextJSON.uuid;
console.log(uuid);
}
Maybe you can parse the string yourself to exclude everything outside of {} ?
var apiResponse = 'Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null';
var apiResponse_fixed = apiResponse.substring((apiResponse.indexOf("{") - 1), (apiResponse.lastIndexOf("}") + 1));
var json_obj = JSON.parse(apiResponse_fixed);
console.log(json_obj.uuid);
Replace the non-JSON features, and then interpret as JSON
Looks like the server owner has been a bit lazy, and programmed an error response which contains a JSON-like interior section but surrounded by a couple of non-JSON elements.
If you are desperate to resolve the situation and have no ability to fix the server output format, here is my suggestion:
notQuiteJson = 'Response: Status=200, Text: {"createdTime":"2017-05-08T14:47:56Z","lastUpdatedTime":"2017-05-08T14:47:56Z","createdMode":"API","uuid":"e333c1-3599-36d7-9ef5-dc22c79a4a52","userId":"anonymous"}, Error Message: null';
madeJson = notQuiteJson.replace('Response: Status=200, Text:','{"Response": {"Status":200}, "Text":').replace('Error Message: null','"ErrorMessage": null}')
obj = JSON.parse(madeJson)
console.log(obj.Text.uuid) // Result: "e333c1-3599-36d7-9ef5-dc22c79a4a52"
Of course this only works if the error message is always exactly this. In reality you may want to use a 3-digit wildcard to cover a range of "Status=" codes. But then you would have to also be confident that all the error modes produce the same non-JSON text at the start and end of the response.
Disclaimer
#sp00m and #Bergi, don't kill me: you are right of course, but this is just for if the poster has no choice in the matter 8-)
I'm building a Javascript chat bot for something, and I ran into an issue:
I use string.split() to tokenize my input like this:
tokens = message.split(" ");
Now my problem is that I need 4 tokens to make the command, and 1 token to have a message.
when I do this:
!finbot msg testuser 12345 Hello sir, this is a test message
these are the tokens I get:
["!finbot", "msg", "testuser", "12345", "Hello", "sir,", "this", "is", "a", "test", "message"]
However, how can I make it that it will be like this:
["!finbot", "msg", "testuser", "12345", "Hello sir, this is a test message"]
The reason I want it like this is because the first token (token[0]) is the call, the second (token[1]) is the command, the third (token[2]) is the user, the fourth (token[3]) is the password (as it's a password protected message thing... just for fun) and the fifth (token[4]) is the actual message.
Right now, it would just send Hello because I only use the 5th token.
the reason why I can't just go like message = token[4] + token[5]; etc. is because messages are not always exactly 3 words, or not exactly 4 words etc.
I hope I gave enough information for you to help me.
If you guys know the answer (or know a better way to do this) please tell me so.
Thanks!
Use the limit parameter of String.split:
tokens = message.split(" ", 4);
From there, you just need to get the message from the string. Reusing this answer for its nthIndex() function, you can get the index of the 4th occurrence of the space character, and take whatever comes after it.
var message = message.substring(nthIndex(message, ' ', 4))
Or if you need it in your tokens array:
tokens[4] = message.substring(nthIndex(message, ' ', 4))
I would probably start by taking the string like you did, and tokenizing it:
const myInput = string.split(" "):
If you're using JS ES6, you should be able to do something like:
const [call, command, userName, password, ...messageTokens] = myInput;
const message = messageTokens.join(" ");
However, if you don't have access to the spread operator, you can do the same like this (it's just much more verbose):
const call = myInput.shift();
const command = myInput.shift();
const userName = myInput.shift();
const password = myInput.shift();
const message = myInput.join(" ");
If you need them as an array again, now you can just join those parts:
const output = [call, command, userName, password, message];
If you can use es6 you can do:
let [c1, c2, c3, c4, ...rest] = input.split (" ");
let msg = rest.join (" ");
You could revert to regexp given that you defined your format as "4 tokens of not-space separated with spaces followed by message":
function tokenize(msg) {
return (/^(\S+) (\S+) (\S+) (\S+) (.*)$/.exec(msg) || []).slice(1, 6);
}
This has the perhaps unwanted behaviour of returning an empty array if your msg does not actually match the spec. Remove the ... || [] and handle accordingly, if that's not acceptable. The amount of tokens is also fixed to 4 + the required message. For a more generic approach you could:
function tokenizer(msg, nTokens) {
var token = /(\S+)\s*/g, tokens = [], match;
while (nTokens && (match = token.exec(msg))) {
tokens.push(match[1]);
nTokens -= 1; // or nTokens--, whichever is your style
}
if (nTokens) {
// exec() returned null, could not match enough tokens
throw new Error('EOL when reading tokens');
}
tokens.push(msg.slice(token.lastIndex));
return tokens;
}
This uses the global feature of regexp objects in Javascript to test against the same string repeatedly and uses the lastIndex property to slice after the last matched token for the rest.
Given
var msg = '!finbot msg testuser 12345 Hello sir, this is a test message';
then
> tokenizer(msg, 4)
[ '!finbot',
'msg',
'testuser',
'12345',
'Hello sir, this is a test message' ]
> tokenizer(msg, 3)
[ '!finbot',
'msg',
'testuser',
'12345 Hello sir, this is a test message' ]
> tokenizer(msg, 2)
[ '!finbot',
'msg',
'testuser 12345 Hello sir, this is a test message' ]
Note that an empty string will always be appended to returned array, even if the given message string contains only tokens:
> tokenizer('asdf', 1)
[ 'asdf', '' ] // An empty "message" at the end