I receive a set of functions in text for another software program which I need to modify and then save and am trying to find the best way to do this.
I could receive a text like this:
Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)
I would like to be able to add text directly after Sum( where it is NOT immediately followed by {< Ideally my end result would like this:
Sum(TEXT_I_WANT_TO_ADD Revenue) + Sum({<CostCentre={'$(=Sum(TEXT_I_WANT_TO_ADD FIELD))'}>}COGS)
Any ideas how to achieve this in a simple way? So far my only idea was to use split and then look at the next object of the array to determine if it contains {<, however I am wondering if there is an easier way to do this.
My try (which works and but is hard to follow and not sure if it will always work):
let text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
let input_text = 'TEXT_I_WANT_TO_ADD ';
let split_text = 'Sum('
let split = text.split(split_text);
console.log(split);
let final_text = '';
for (let i in split) {
let split_modified;
// Not last item
if (i < split.length - 1) {
let next = (parseInt(i) + parseInt(1));
// Does not include {<
console.log(next, split[next]);
if (!split[next].includes('{<')) {
final_text += split_text + input_text;
}
// Does include {<
else {
final_text += split_text + split[next]
}
}
// Last item
else {
final_text += split[i]
}
}
console.log(final_text);
Any ideas how to do this is a better, easier way?
You can capture the word inside the parenthesis of Sum() and replace it :
const input_text = "TEXT_I_WANT_TO_ADD ";
const text = `Sum(Revenue) + Sum({<CostCentre={'$(=Sum(FIELD))'}>}COGS)`;
const result = text.replace(/Sum\(\w+\)/g, match => `Sum(${input_text})`);
console.log(result);
sorry I just started with javascrippt and html and I am having trouble finding out what the unexpected identifier is?
here is my function
function fillSearchPlayer(data){
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i]
var item = '<tr><td>'p.firstname + ' ' + p.lastname'</td><td>'p.job'</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>'
$('#searchPlayers tbody').append('item');
}
}
maybe you guys could help me, it's saying its coming from the line that starts with "var item"
'<tr><td>'p.firstname look like you missed a plus sign over there. The other thing is .append('item'); - you probably intented to do .append(item);.
As the guys mentioned in the direct comments above you should try to use some templating engine instead of constructing the strings the way you did it.
I would recommend you to read these pieces:
Handlebars - simple and convenient template engine in JavaScript - give it a try!
Template strings in ES2016 - a cleaner way to do what you did with manual string concatenation
There are several errors. String concatenation works with +, and you're missing a semicolon.
Try:
function fillSearchPlayer(data) {
$('#searchPlayers tbody').html('');
for (var i = data.length - 1; i >= 0; i--) {
var p = data[i];
var item = '<tr><td>' + p.firstname + ' ' + p.lastname + '</td><td>' + p.job + '</td><td><button class="cbtn" onclick="requestPlayer("'+ p.identifier + '")">More</button></td></tr>';
$('#searchPlayers tbody').append('item');
}
}
The var item = ... item mixes variable and literal definitions without the real concatenation going on. Just put a + between each varying element to achieve your goal.
You need to enclose the concatenation operator around the p.job variable.
Your assignment should look like this...
var item = '<tr><td>'+p.firstname + ' ' + p.lastname+'</td><td>'+p.job+'</td><td><button class="cbtn" onclick=requestPlayer('+ p.identifier + ')>More</button></td></tr>'
I am getting issues to convert unicode and render in a nice HTML code.
Here is the information i have as an input in my Json file
`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`
I would like this to render as below in
CLIENT:
- client1: Project 1
- Client2: etc...
It currently renders like this :
`CLIENT: - Client1: Project1Â - Client2: etc...`
I looked everywhere but could not find a function that could handle all unicodes to decode in nice html code.
Thanks in advance!
Maybe you can take a look at this:
How do I replace all line breaks in a string with tags?
You do this:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
before insert into the html.
If you are using javascript, you can use this fragment
<script>
var c = decodeURIComponent(escape(`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`));
c = c.replace(/(?:\r\n|\r|\n)/g, '');
c = c.replace(':-', ': - ');
document.write(c);
</script>
Ok I managed to make this work with the below function:
function strFormat(str) {
var c= decodeURIComponent(escape(str));
c= c.replace(/(?:\r\n|\r|\n)/g, '<br />');
c= c.replace(':-', ': - ');
return c;
}
Let me know if there are any cleaner way to do this?
i'm doing an application with ajax using jQuery and some other tools, and in some part i want to retrieve data with ajax using a classic ASP backend, i saw that exists a good implementation of a JSON class in AXE (Asp extreme edition) framework, and i used it but currently i don't understand how to use it well.
Edit: based on the correct answer of JSON.Stringify fails on Scripting.Dictionary objects Thread, i decided to make a custom function to process Recordsets.
Edit 2: Now i'm losing the value data when call JSON.stringify inside function JSONStringify(object).
when the Recordset is passed as value to JSONStringify everything is ok but when JSON.stringify is executed, the "value" parameter that must contain the recordset becomes undefined
What i'm expecting (example)
passing a Recordset with from a SQL query SELECT name, tel FROM users a see an output like this
[
{"name":"Jonh Smith", "tel":"12345678"},
{"name":"April Michelson", "tel":"77788802"},
...
]
passing a Dictionary and see something similar based in the elements declared in dictionary.
{
"element1":"value1",
"element2":"value2",
"element3":"value3",
"element4":"value4",
"element5":"value5"
}
and if i like to support other type object i can do it expanding the function
Source Code
getcatalogos.asp
<!--#include file="../includes/conexion.asp" -->
<!--#include file="../includes/json2.asp" -->
<!--#include file="../includes/json-stringify-parser.asp" -->
<%
Response.ContentType = "application/json"
dim aVals(2)
function getCatalogo(tipo, params)
Dim oConn,oCmd,sSQL,oRs,cont2
Dim aData,oPar,cont
dim Info
set oConn = Server.CreateObject("ADODB.Connection")
set oCmd = Server.CreateObject("ADODB.Command")
sWhere = ""
oConn.ConnectionString = strcon
oConn.Open
Set oCmd.ActiveConnection = oConn
select case tipo
case "g"
sSQL = " SELECT cve_gr, descr FROM gr ORDER BY descr ;"
case "z"
sSQL = " SELECT cve_zn, descr FROM zn WHERE cve_gr = ? ORDER BY descr ;"
if IsArray(params) Then
Set oPar=oCmd.CreateParameter (params(0),129,1,2,params(1))
oCmd.Parameters.Append(oPar)
End if
case else
getCatalogo = false
exit function
end select
oCmd.CommandText = sSQL
Set oRs = oCmd.Execute()
if Not oRs.EOF Then
response.write(JSONStringify(oRs))
getCatalogo = true
else
getCatalogo = false
end if
oConn.Close
end function
aVals(0) = "cve_gr"
aVals(1) = request.querystring("gr")
if Not getCatalogo(request.querystring("t"),aVals) Then
%>error<%
end if
%>
json-stringify-parser.asp
<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">
function JSONStringify(object) {
VBSTypeName(object);
return JSON.stringify(object,stringifyData);
}
function stringifyData(holder, key, value) {
var sType = '';
var result;
//response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
sType = VBSTypeName(value);
//response.write('post =' + sType);
//response.write(sType);
switch(sType){
case 'Dictionary':
result = '{';
for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
key = enr.item();
result += '"' + key + '": ' + JSON.stringify(value.Item(key));
};
result += '}';
return(result);
break;
case 'Recordset':
response.write('here!!!');
var sTemp = '';
result = '{';
while(!value.EOF){
if(Len(result) > 0){
result += ',';
}
result += '{';
for (var i = value.Fields.Count - 1; i >= 0; i--){
if(len(sTemp) > 0){
sTemp += ',';
}
sTemp += '"' + value.Fields(i).name + '":' + JSON.stringify( value.Fields(i).value);
};
result += '}';
}
result += '}';
return result;
break;
default:
//response.write(sType);
return(value);
}
// return the value to let it be processed in the usual way
return result;
}
</script>
vbsTyper.asp
<%
Function VBSTypeName(Obj)
dim sType
sType = Cstr(TypeName(Obj))
response.write(sType)
VBSTypeName = sType
End Function
%>
This:
response.write(JSON.stringify(oRs))
Should read something like this:
Do Until oRS.EOF
response.write(JSON.stringify(oRs("cve_gr") & ":" & oRs("descr"))
oRS.MoveNext
Loop
kind of achieve it...
Short version: i had to modify the json2.asp and hack the stringify() function definition to make it works.
Long Version
later of see every line of code and giving up on the problem. i decided to take a look into json2.asp (AXE Framework) and try to see what it happening there.
look what i see:
from the lines 682 to 687 theres a validation if a custom stringy parser is found but later doesn't do anything ... only returns the Object value.
there's speculation from here, because i don't understand well how works every Javascript implementation, but implying that the original code runs well, that a standart javascript interpreter (read everything else but microsoft here) will force a serialization of the object in this sutuation, but the JScript interpreter try to parse the object and pass the value as null. resulting in that every function that uses a custom stringyfier can't read the object passed in the function.
what i did to resolve ok i inserted this chunk of code before line 688, forcing to execute the custom stringyfier with value directly passed as argument avoiding the implicit parsing.
// Hack & patch to deliver the stringify-ing of the object correctly
// IDK if this is CORRECT or dont but it works in VbScript
if(replacer){
var textval = rep(this,'',value);
value = textval;
}
later i had to do some changes in json-stringify-parser.asp because i had to fix some bugs resulting in this code
<!--#include file="vbsTyper.asp" -->
<script runat="server" language="JScript">
function JSONStringify(object) {
//VBSTypeName(object);
return JSON.stringify(object,stringifyData,4);
}
function stringifyData(holder, key, value) {
var sType = '';
var result;
//response.write('pre...holder=' + holder + ',key=' + key + ',value=' + value);
sType = VBSTypeName(value);
//response.write('post =' + sType);
//response.write(sType);
switch(sType){
case 'Dictionary':
result = '{';
for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()){
key = enr.item();
result += '"' + key + '": ' + JSON.stringify(value.Item(key));
};
result += '}';
return(result);
break;
case 'Recordset':
//response.write('here!!!');
var sTemp;
result = '';
while(!value.EOF){
if(result.length > 0){
result += ',';
}
result += '{';
sTemp=''
for (var i = 0; i < value.fields.Count; i++){
if(sTemp.length > 0){
sTemp += ',';
}
//response.write("i=" + i + ",");
sTemp += '"' + value.fields.item(i).name + '":' + JSON.stringify( value.fields.item(i).value);
};
result += sTemp + '}';
value.moveNext();
}
result = '{' + result + '}';
return result;
break;
default:
//response.write(sType);
return(value);
}
// return the value to let it be processed in the usual way
return result;
}
</script>
the part to parse a Recordset works, the part to parse a dictionary is same like the shown in JSON.Stringify fails on Scripting.Dictionary objects (a.k.a. i haven't tested yet) but for now i'm done with this.
testing my changes with a recordset object results in this output
"{
{\"clave\":\"BC\",\"descripcion\":\"Cal\"},
{\"clave\":\"CT\",\"descripcion\":\"Center\"},
{\"clave\":\"NE\",\"descripcion\":\"Norw\"},
{\"clave\":\"NO\",\"descripcion\":\"Nore\"},
{\"clave\":\"NT\",\"descripcion\":\"North\"},
{\"clave\":\"OC\",\"descripcion\":\"East\"},
{\"clave\":\"OR\",\"descripcion\":\"West\"},
{\"clave\":\"PE\",\"descripcion\":\"Pen\"},
{\"clave\":\"SE\",\"descripcion\":\"Southe\"},
{\"clave\":\"ZM\",\"descripcion\":\"Met\"}
}"
Questions Left
question that i have left withis kind of hack.
it's Ok that the output has (") character at the beggining and the
end and i everything else has escape sencuences ?? or it's something
that should not occurs.
this kind of hack is really wrong ... i can do it better, in this
kind of situation ?
it's something wrong in my conclusion or arguments ??
What's the wrong with this Javascript line?
user: h.reem
domain: somedomain
var target = "//account/win/winlogin.aspx" +
"?username=" +
user.toString() +
"&domain=" +
domain.toString();
the resutl is always:
//account/win/winlogin.aspx?username=h.reem
Any idea!!
alert(user + "X") shows only h.reem
The ActiveX component is probably returning a null terminated string (I've seen this with Scripting.TypeLib & a couple of the AD objects for example) so concatenating it with another string fails. (You can verify this if 0 === user.charCodeAt(user.length - 1)).
You will need remove the last character before using the string;
user = user.substr(0, user.length - 1);
try:
var sUser = user.toString();
var sDomain = domain.toString();
var target = "//account/win/winlogin.aspx" + "?username=" + sUser + "&domain=" + sDomain;
The above might not fix your problem but it should expose it - Could be that your user.toString() method isn't returning a string and is short-circuiting things... If this doesn't answer your question I'd be glad to assist further, but it would be helpful if you posted the implementation or source of "user" somewhere ...