Split long string into text chunks with jQuery - javascript

I have a long string that needs to be sliced into separated chunks inside an array, with a predefined length limit the chunks. Some rules apply:
If the limit cuts a word, then the word is separated for the next chunk.
Slices must be trimmed (no spaces at the beginning or end of the array item).
Special punctuation .,!? should stay with the word, and not be sent to the next chunk.
Original text: I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.
Result with current code ["I am totally", " unappreciated in my time", ". You can run this whole", " park from this room with", " minimal staff for up to ", "3 days. You think that", " kind of automation is ea", "sy? Or cheap? You know", " anybody who can network ", "8 connection machines", " and debug 2 million line", "s of code for what I bid", " for this job? Because if", " he can I'd like to see h", "im try."]
...it should actually be:
["I am totally", "unappreciated in my time.", "You can run this whole", "park from this room with", "minimal staff for up to 3", "days. You think that kind", "of automation is easy?", "Or cheap? You know anybody", "who can network 8", "connection machines and", "debug 2 million lines of", "code for what I bid for", "this job? Because if he", "can I'd like to see him", "try."]
As you can see, I'm still having trouble with rules 2 and 3.
This is my current code (you can check the working demo in jsfiddle):
function text_split(string, limit, pos, lines) {
//variables
if(!pos) pos = 0;
if(!lines) lines = [];
var length = string.val().length;
var length_current;
//cut string
var split = string.val().substr(pos, limit);
if(/^\S/.test(string.val().substr(pos, limit))) {
//check if it is cutting a word
split = split.replace(/\s+\S*$/, "");
}
//current string length
length_current = split.length;
//current position
pos_current = length_current + pos;
//what to do
if(pos_current < length) {
lines.push(split);
return text_split(string, limit, pos_current, lines);
} else {
console.log(lines);
return lines;
}
}
$(function(){
$('#button').click(function(){
text_split($('#textarea'), 25);
});
});
The html form for the demo:
<textarea id="textarea" rows="10" cols="80">I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.</textarea>
<button id="button">demo</button>

Example for 25 characters max, you can use this pattern:
/\S[\s\S]{0,23}\S(?=\s|$)/g
demo
code example:
var text = " I am totally unappreciated in my time. You can run this whole park from this room with minimal staff for up to 3 days. You think that kind of automation is easy? Or cheap? You know anybody who can network 8 connection machines and debug 2 million lines of code for what I bid for this job? Because if he can I'd like to see him try.";
var myRe = /\S[\s\S]{0,23}\S(?=\s|$)/g;
var m;
var result = new Array();
while ((m = myRe.exec(text)) !== null) {
result.push(m[0]);
}
console.log(result);
Note: if you need to choose dynamically the max size, you must use the alternative syntax to define your RegExp object:
var n = 25;
var myRe = new RegExp("\\S[\\s\\S]{0," + (n-2) + "}\\S(?=\\s|$)", "g");
pattern details:
\S # a non-space character (it is obviously preceded by a space
# or the start of the string since the previous match
# ends before a space)
[\s\S]{0,23} # between 0 or 23 characters
\S(?=\s|$) # a non-space character followed by a space or the end of the string
Note that (?=\s|$) can be replaced with (?!\S).

Related

JS String concatenate encoding issue

I have two html datalists, and I get their input values to query a json file. I first search the keys of my json file which are college majors, their values are their courses. So once the object key equals the program, I return that element because I want to further query that element with the second input field which is a course number. This step is always successful at returning the correct program courses corresponding to the program input.
The second step is where things go bad. I want to now take that program element and look through all the names of the courses in that program. I concatenate the two input fields, program + " " + course. The program is a major like "CSE" or "I S" and the course is any 3 digit number like "143" or "310". Each object element in the program has a string name attribute like "CSE 143". This name attribute does not equal the program + " " + course even though they are both of type string and the same value WHEN I am looking at a program that has a space in it. For example, I want to find the course "I S 310". I successfully search for the program name that equals "I S". I iterate through the keys and find the correct element value using this operation Object.keys(jsondata[index]) == program. program is a variable containing the string "I S". As stated previously, this is successful, but if I iterate through the children of that objectkey value to find id, like programdata[index].children == program + " " + course, it doesnt work. If I instead hardcode the value, programdata[index].children == "I S 310", it works! This leads me to believe that the concatenation operation for these two variables changes the encoding of the string. According to console.log, the type of "I S 310" and program + " " + course are both Strings except they output a different encodeURIComponent().
Ill write what the output to the console is since im not reputable enough:
Step 1
function getProgramCourses(data, program) {
var programKeys = Object.keys(data);
for (var i = 0; i < programKeys.length; i++) {
if (Object.keys(data[i]) == program) {
return data[i][Object.keys(data[i])];
}
}
return objs
}
program = "CSE"
console.log(program)
console.log(encodeURIComponent(program));
Output:
CSE
CSE
program = "I S"
console.log(program)
console.log(encodeURIComponent(program));
Output:
I S
I%C2%A0S
Those unencoded hidden characters dont affect this first step of finding the courses offered by the "I S" program. Now when I want to find a specific course within the "I S" program like "I S 310":
Step 2
//data is object array of all courses in this program
function getCourse(data, program, course) {
pc = program + " " course;
for (var i = 0; i < data.length; i++) {
if (data[i].name == pc) {
return data[i];
}
}
}
"CSE" = program and "143" = course
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
CSE 142
CSE%20142
["I S" = program and "310" = course][2]
pc = program + " " + course;
console.log(pc)
console.log(encodeURIComponent(pc));
Output:
I S 310
I%C2%A0S%20310
This second step only works for programs that dont have spaces like "CSE" or "MATH". Doesnt work for "A A" or "I S". data[i].name is type String and so is pc.
Sorry about the lengthy post, I just wanted to be as descriptive as possible. Any help would be greatly appreciated.
Basically
Here is my problem:
console.log("A A 198")
console.log(encodeURIComponent("A A 198"))
console.log(program + " " + course)
console.log(encodeURIComponent(program + " " + course))
Output:
A A 198
A%20A%20198
A A 198
A%C2%A0A%20198
not equal
Your program variable contains a character which is like a space but isn't a space. Make sure it isn't an encoding issue, else you can fix this with this simple code.
encodeURIComponent(program.replace(/\u00a0/g, ' ') + ' ' + course)

Break up a string in JS

I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());

Why script will sometimes launch ExtendScript Toolkit & just stall

Any ideas why sometimes when the script is called to run it will launch ExtendScript Toolkit & just stall? I think it maybe when there is a lot of text to go through. Not sure that is the case every time. See Pic below script.
If it stops it stops on the line: var new_string = this_text_frame.contents.replace(search_string, replace_string);
// Version 3
function myReplace(search_string, replace_string) {
var active_doc = app.activeDocument;
var text_frames = active_doc.textFrames;
if (text_frames.length > 0)
{
for (var i = 0 ; i < text_frames.length; i++)
{
var this_text_frame = text_frames[i];
var new_string = this_text_frame.contents.replace(search_string, replace_string);
if (new_string != this_text_frame.contents)
{
this_text_frame.contents = new_string;
}
}
}
}
myReplace(/^PRG.*/i, "");
myReplace(/.*EBOM.*/i, "");
myReplace(/^PH.*0000.*/i, "");
myReplace(/^PH.*00\/.*/i, "");
// N or W & 6 #'s & -S_ EX. N123456-S_ REPLACE with: N123456-S??? (THIS NEEDS TO BE ABOVE _ REPLACED BY SPACE)
myReplace(/([NW]\d{6}-S)_/i, "$1??? ");
myReplace(/_/gi, " ");
// 6 #'s & - or no - & 7 #'s & 1 to 3 #'s & - EX: 123456-1234567/123- REPLACE with: -123456-
myReplace(/(\d{6})-?\d{7}\/\d\d?\d?-/i, "-$1-");
myReplace(/(\d{6})-?\d{7}-\/\d\d?\d?-/i, "-$1-");
myReplace(/([NW]\d{6}-S)-INS-\d\d\/\d\d?-/i, "$1??? ");
myReplace(/-INS-\d\d\/\d\d?-/i, "* ");
// - That is only followed by one more - & Not having PIA & - & 2 to 3 #'s & / & 1 to 3 #'s & - EX: -7NPSJ_RH-001/9- REPLACE with * & Space
myReplace(/-[^-]*-\d\d\d?\/\d\d?\d?-/i, "* ");
myReplace(/ ?ASSEMBLY/gi, " ASY");
myReplace(/ ASS?Y+$| ASS?Y - | ASS?Y -| ASS?Y | ASS?Y- | ASS?Y-/gi, " ASY - ");
myReplace(/(MCA-|DS-?C1-?)/i, "-");
myReplace(/^DS-|^DI-|^PH-|MCA|^PAF-|^PAF|^FDR-|^FDR/i, "");
myReplace(/VIEW ([a-z])/i, "TTEMPP $1");
myReplace(/ ?\(?V?I?EW\)| ?\(?VIE[W)]?|^W\)| ?\(VI+$|^ ?\(VI| ?\(V+$|^ ?\(V| ?\(+$|^ ?\)/i, "");
myReplace(/TTEMPP ([a-z])/i, "VIEW $1");
myReplace(/([NW]\d{6}-S)-/i, "$1??? ");
myReplace(/([NW]\d{6}-S)\/.-/i, "$1??? ");
// Needs to be in this order
myReplace(/ AND /i, "&");
myReplace(/WASHER/i, "WSHR");
myReplace(/BOLT/i, "BLT");
myReplace(/STUD/i, "STU");
myReplace(/([SCREW|SC|NUT|BLT|STU])&WSHR/i, "$1 & WSHR");
myReplace(/\?\?\? SCREW &/i, "??? SC &");
myReplace(/\?\?\? SC [^&]/i, "??? SCREW ");
myReplace(/(\?\?\? SC & WSHR).*/i, "$1");
myReplace(/(\?\?\? SCREW).*/i, "$1");
myReplace(/(\?\?\? NUT & WSHR).*/i, "$1");
myReplace(/\?\?\? NUT [^&].*/i, "??? NUT");
myReplace(/(\?\?\? BLT & WSHR).*/i, "$1");
myReplace(/\?\?\? BLT [^&].*/i, "??? BLT");
myReplace(/(\?\?\? STU & WSHR).*/i, "$1");
myReplace(/\?\?\? STU [^&].*/i, "??? STU");
myReplace(/--/gi, "-");
if ( app.documents.length > 0 && app.activeDocument.textFrames.length > 0 ) {
// Set the value of the word to look for
searchWord1 = "*";
//searchWord2 = "The";
// Iterate through all words in the document
// the words that match searchWord
for ( i = 0; i < app.activeDocument.textFrames.length; i++ ) {
textArt = activeDocument.textFrames[i];
for ( j = 0; j < textArt.characters.length; j++) {
word = textArt.characters[j];
if ( word.contents == searchWord1 ) {
word.verticalScale = 120;
word.horizontalScale = 140;
word.baselineShift = -3;
}
}
}
}
[img]http://i.imgur.com/9IRy9.jpg[/img]
This javascript is call to run from a applescript.
set Apps_Folder to (path to applications folder as text)
set Scripts_Path to "Adobe Illustrator CS5:Presets.localized:en_US:Scripts:"
set JS_FileName to "Text Find & Replace.jsx"
--
try
set JS_File to Apps_Folder & Scripts_Path & JS_FileName as alias
tell application "Adobe Illustrator"
do javascript JS_File show debugger on runtime error
end tell
on error
display dialog "Script file '" & JS_FileName & "' NOT found?" giving up after 2
end try
Did you search for your Errorcode?
1346458189 ('MRAP')
It is at the bottom of the ESTK. have a look here http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/scripting/cs6/Readme.txt
Its not "MRAP", its "PARM" but the number fits.
"An Illustrator error occurred: 1346458189 ('PARM')" alert (1459349)
Affects: JavaScript
Problem:
This alert may appear when carelessly written scripts are repeatedly
run in Illustrator from the ExtendScript Toolkit.
Each script run is executed within the same persistent ExtendScript
engine within Illustrator. The net effect is that the state of
the ExtendScript engine is cumulative across all scripts that
ran previously.
The following issues with script code can cause this problem:
Reading uninitialized variables.
Global namespace conflicts, as when two globals from different
scripts have the same name.
In your script are some uninitialized variables
searchWord1 = "*";
textArt = activeDocument.textFrames[i];
word = textArt.characters[j];
Its not "MRAP", its "PARM" but the number fits.
actually, on MacOS "MRAP" is the correct sentence returned. "PARM" is for windows.
My experience with this error :
I run a 2 000 lines' javascript.
I have to check for 700 folders contained each between 1 - 15 differents .ai files.
on MACOS 10.7, I got this error 2 times for 15 folders, never the same file. (CS6)
on Win8 I got this error 1 time for 5 folders, never the same file. (CC 2014)
on win7 I got this error 1 time for 100 folders, never the same file. (CC 2014 or CS6)
and finally I run it on a just installed win7 and I got no error, the script was running 10 hours without interruption. (CC 2014 or CS 6)
While I'm sure #fabianmoronzirfas has the technically correct and most likely answer, my recent experience with error 1346458189 is that is appears to be Illustrator's equivalent of Microsoft's infamous "Unknown error." That is, it appears to be the catch-all error for anything Adobe didn't write a more informative error trap for.
For me, this unhelpful error was a result of trying to set the artboard too small (below 1 point). Clearly, Illustrator doesn't do enough bounds checking. For others, as far as I could tell from searching the net, it comes from a smattering of reasons. Including, possibly, memory and other errors from within Illustrator's script processor, which would be one way to account for it's randomness in some scenarios. Most likely, however, I suspect it is usually something solvable with more durable code.

Adding colors to terminal prompt results in large white space

I'm working on a simple cli script and wanted to add some color to the following code:
rl.question('Enter destination path: ', function(answer) {
// ...
});
rl.write('/home/' + user + '/bin');
Which displays in the terminal:
Enter destination path: /home/jmcateer/bin_
But I wanted to add some color to the prompt I did the following:
rl.question('\u001b[1;36mEnter destination path:\u001b[0m ', function(answer) {
});
rl.write('/home/' + user + '/bin');
And the command line prompt ended up displaying:
Enter destination path: /home/jmcateer/bin_
It works but there's a huge amount of white space I'd prefer weren't there. Does anyone have any ideas on how to deal with this?
Edit:
I can't delete the white space by backspacing through it... when I try to use the backspace key the white space jumps to the other end like so
Enter destination path: /home/jmcateer/bin_
Enter destination path: /home/jmcateer/bi _
Enter destination path: /home/jmcateer/b _
...
Enter destination path: _
At that point backspace has no effect.
When you call rl.setPrompt(prompt, length) without its second argument, the internal _promptLength variable is set to the length of the prompt string; ANSI X3.64 escape sequences are not interpreted. The internal _getCursorPos method computes the cursor position from _promptLength][3]; as such, the inclusion of the escape sequences in the length results in the cursor being positioned further away than it should be.
To resolve this problem fully, Node's readline library should parse the ANSI escape sequences when setting _promptLength. To work around this problem, you can manually calculate the length of the prompt string without the escape sequences and pass that as the second argument to rl.setPrompt(prompt, length).
I also ran into a similar issue. Basil Crow is correct in his excellent answer on the cause of the problem in that it is indeed the ANSI escape sequences that are causing the length glitch; however, Interface.setPrompt() is not just the problem—it is the solution!
It seems that this misreading of the length (something I artfully avoided while playing around in bash) affects the entire Interface object's writeout process, i.e. anything that calls Interface.setPrompt() in any capacity will be afflicted when the length parameter is left not specified.
In order to overcome this problem, you can do one of two things:
Redefine Interface.setPrompt() to always specify a length for prompt output so that methods like Interface.question() function properly again:
// I'm using the 'color' npm library for the sake of convenience. It is not required
// and you can use normal regex to strip color codes and what not.
var colors = require('colors'),
readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
/* Overcome some bugs in the Nodejs readline implementation */
rl._setPrompt = rl.setPrompt;
rl.setPrompt = function(prompt, length)
{
rl._setPrompt(prompt, length ? length : prompt.split(/[\r\n]/).pop().stripColors.length);
};
var str = '[' + '?'.green + '] Blackbeard walks under the black flag with a ____? ';
rl.question(str, function(answer)
{
var answ = 'scallywag swagger';
console.log(
'You answered "' + ((answer == answ) ? answer.green : answer.red)
+ '". The correct answer is', '"' + answ.green + '".');
});
Redefine Interface.write() to use Interface.setPrompt() passing both the writeout string and the true length of the string to the setPrompt method:
var colors = require('colors'),
readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
/* Overcome some bugs in the Nodejs readline implementation */
rl._write = rl.write;
rl.write = function(d, key)
{
// "key" functionality is lost, but if you care enough you can add it back
rl.setPrompt(d, d.split(/[\r\n]/).pop().stripColors.length);
rl.prompt(true);
};
var str = '[' + '?'.green + '] Blackbeard walks under the black flag with a ____? ';
rl.write(str);
rl.on('line', function(answer)
{
var answ = 'scallywag swagger';
console.log(
'You answered "' + ((answer == answ) ? answer.green : answer.red)
+ '". The correct answer is', '"' + answ.green + '".');
rl.prompt(true);
});
The results for both are the same:
Or you can do both. Or you can modify the readline.Interface.prototype directly (and have your fix applied globally) instead of the object instances themselves. Lots of options here.
Hope this helps someone!
EDIT—See also: https://github.com/joyent/node/issues/3860
Sure, you'll want to modify your rl.write string with the CSI sequence n D where n is the number of characters to move your cursor back.
Here is a snippet to experiment with:
var rl = require('readline').createInterface({input: process.stdin, output: process.stdout});
rl.question('\u001b[1;36mEnter destination path: \u001b[0m', function(answer) {
});
rl.write('\u001b[11 D/home/jp/bin');
Notice the 11 and the D in the last line? The D stands for the number of characters to move back. 11 is obviously then the number of characters.
See this for all of the fun terminal codes: http://en.wikipedia.org/wiki/ANSI_escape_code

String replace does not work in javascript (with double quotes)

Please look at the following code, If i do not perform the "Sanitary" steps in the function the code does not replace the string values.
can some one help me understand this?
Complete code :
<script type="text/javascript">
function replaceString(orgStr,oldStr,newStr){
//############# Sanitary Steps #############//
oldStr = oldStr .replace(/[ ]+/g,"$");
oldStr = oldStr .replace(/[$]+/g," ");
orgStr = orgStr .replace(/[ ]+/g,"$");
orgStr = orgStr .replace(/[$]+/g," ");
newStr = newStr .replace(/[ ]+/g,"$");
newStr = newStr .replace(/[$]+/g," ");
//############# Sanitary Steps #############//
orgStr = orgStr.replace(oldStr,newStr);
if(orgStr.indexOf(oldStr) != -1){
orgStr = replaceString(orgStr,oldStr,newStr)
}
return orgStr;
}
var fields = ['"Employee Expense Facts"."Total Expense"','"Expense Amount by Expense Type Facts"."Airfare Expense Amount"'];
var selectedField = 0;
var selectedField = 0;
var qry = 'SELECT rcount(1) s_0, "Employee Expenses"."Time"."Date" s_1, "Employee Expenses"."Employee Expense Facts"."Total Expense" s_2 FROM "Employee Expenses" WHERE ("Employee Expense Facts"."Total Expense" IS NOT NULL) ORDER BY 1, 2 ASC NULLS LAST WHERE ("Employee Expense Facts"."Total Expense" IS NOT NULL) ORDER BY 1, 2 ASC NULLS LAST';
qry = qry .replace(/[\n\t\r]+/g," ");
var qry2 = replaceString(qry,""+fields[0],""+fields[1]);
console.log(qry2);
</script>
Help me understand why I need to perform those sanitary steps???
I found the solution by just trial and error method.
My advise would be: Throw away all that code!
Now start again, handing the data from the client to the server via a normal formsubmit or an ajax call. Now process them serverside.
And always remember rule number one:
1) You can never trust all users to behave the way YOU want.
Thats why never ever create your SQL clientside!
The Issue is in the SQL itself:
SELECT rcount(1) s_0,
"Employee Expenses"."Time"."Date" s_1,
"Employee Expenses"."Employee Expense Facts"."Total Expense" s_2
FROM "Employee Expenses"
WHERE ("Employee Expense Facts"."Total Expense" IS NOT NULL)
ORDER BY 1, 2 ASC NULLS LAST
WHERE ("Employee Expense Facts"."Total Expense" IS NOT NULL)
ORDER BY 1, 2 ASC NULLS LAST
I found out that there are double quotes which even after using escape characters are not replaced. I have tried replacing the (") with special characters and then performing the string replace and yet not able to do that successfully.
Whats surprising is if you create this function on the local HTML file this works without sanitary code. but when i upload the same code on the server it does not work. for that i had to put in place the sanitary lines.
If any one else figures out why this is caused please do let me know :)
thanks
vx

Categories