Parsing text into javascript String - javascript

I am trying to parse some text into javascript strings. In essence I have a String in javascript containing what would be another javascript string. Here are some samples that I have in my tests:
input1: '"This \\"should\\" work"'
output1: 'This "should" also work'
input2: '"Another working \\nstring\\n with newlines"'
output2: 'Another working \nstring\n with newlines'
// Should throw an exception since it would escape the last ":
input3: '"This should not work\\"'
// Should throw an exception since it contains an illegal newline
input4: '"This \n should also not work"'
I was considering using eval on the input strings but it feels like a hack and I am unsure if it is safe. It doesn't yield an error on the input3 sample when I try it in Node.It works when running my tests but not when used I run: eval('"This should not work\\"') in Node directly.
How can I parse the above sample inputs to their corresponding outputs and still get errors for the bad samples?
EDIT:
My initial atempt:
output = input.slice(1, input.length - 1)
My second atempt:
output = eval(input);
Using eval seems to work , but feels like a hack.

Related

Why driver.execute_script function is giving an unexpected token error for special characters and numbers in string?

I have written a python script using selenium library which will send all the list of keywords to textarea. Since this send_keys method is very slow, so i have chosen to do the same action using execute script which is pasting all the keywords to textarea in fraction of seconds. However for some keywords in my list which ends with tilde & numeric value for example : '"Very fast"~2'. the double quotes enclosed and ~2 are part of my keyword that i wanted to paste along with my words, they are not part of python string format they are actually required to paste with tilde 2.
list_of_words = ['"Fresh apple"','"green apple"~2','"spoiled apple"~1']
# Converting list to string since value in execute script accept only string not list
list_to_string = str(list_of_words)
driver.execute_script("document.getElementById('section').getElementsByTagName('textarea')[0].value="+list_to_string )
why this code is giving me an error called : Javascript Unexpected token '~'
I cannot replace the ~2 character to execute since i need them in my textarea. the output shall be pasting all keywords in the list to textarea as shown below without any commas because since i converted the list to string so now my string of all keywords has commas.
expected output in textarea
"Fresh apple"
"green apple"~2
"spoiled apple"~1
As per the documentation or str
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.
so using str is not a proper solution, but to answer your question, I am giving the code anyway
So technically you get below as a string including the brackets
['"Fresh apple"', '"green apple"~2', '"spoiled apple"~1']
Now you need to replace [, ], , everything manually so that you will get
"Fresh apple"\n"green apple"~2\n"spoiled apple"~1
above output is your unit test outcome which needs to be sent to browser javascript below is the full code
HTML
<div id="section">
<textarea cols=30 rows=10></textarea>
</div>
Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import time
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
driver.get("http://localhost:8082/test.html")
low = ['"Fresh apple"','"green apple"~2','"spoiled apple"~1']
los = str(low).replace("'","").replace(', ', '\\n')[1:-1]
driver.execute_script("document.getElementById('section').getElementsByTagName('textarea')[0].value='" + los + "'")
time.sleep(10)
Output
Try this:
Define the element's locator using XPATH or CSS_SELECTOR.
driver.execute_script("arguments[0].value='" + list_to_string + "';", <locator of text area>)

How can I replace some calls to JavaScript's eval() with Ext.decode()?

We are trying to get rid of all of our eval() calls in our JavaScript. Unfortunately, I am not much of a JavaScript programmer, and I need some help.
Many of our eval() calls operate on strings, outputs from a web service, that are very JSON-like, for example, we might eval the following string:
ClassMetaData['Asset$Flex'] = {
fields: {
}
,label: 'Flex Fields'
};
I've seen various suggestions on the Internet suggesting Ext.decode(). The documentation for it says - "Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set." The string that I am supplying as an argument isn't legitimate JSON as I understand it (the field names aren't quoted), but Ext.decode() nearly works for me anyway. If I decode the above string, I get an error (why?) - "Uncaught SyntaxError: Unexpected token ;". However, if I remove the trailing semi-colon, and decode, everything seems to be fine.
I am using the following code to determine whether the decode call and the eval call do the same thing:
var evaled = eval(inputString);
var decoded = Ext.decode(inputString.replace(";", "")); // remove trailing ";", if any
console.log("Equal? - " + (JSON.stringify(decoded) == JSON.stringify(evaled)));
Unfortunately, this is not a very good solution. For example, some of the input strings to eval are fairly complex. They may have all sorts of embedded characters - semicolons, HTML character encodings, etc. Decode may complain about some other syntax problem, besides semicolons at the end, and I haven't found a good way to determine where the problem is that decode objects to. (It doesn't say "illegal character in position 67", for example.)
My questions:
Could we, with a small amount of work, create a generic solution
using decode?
Is there an easy way to convert our JSON-like input
into true JSON?
Is there a better way of comparing the results of
eval and decode than JSON.stringify(decoded) == JSON.stringify(evaled)?

adding carriage return don't put the string that follows it at the begining position

I wanted to understand what carriage return is by writint a simple code to console.As carriage return '\r' means
" return to the beginning of the current line without advancing
downward"
But in my code the following string is appended at the end of the line .Why it is behaving like this.I have a string "this is my string" ,then i have carriage return ,and it is followed by another string "that".I thought "that" will be placed at the beginning of the string
console.log("this is my string"+String.fromCharCode(13)+"that");
it prints "this is my stringthat"
Using \r in a string in JavaScript is probably going to give you different results depending on a combination of how the program is being run (in a browser or a standalone engine) and the target of the text (console, alert, a text node in an HTML element etc). It's not clear from your question whether you're running JavaScript in a browser, but (assuming you are) you're going to get different results for different browsers. Internet Explorer's console treats \r as a newline character (\n) while most other browsers will ignore it. I doubt any browser implementation of console is going to give you the behavior you've described.
Note that \r is not a string processing instruction, it's a character. Doing this:
var aString="one\r2";
is never going to result in
aString == "2ne"
or
aString == "2one"
or
aString == "one2"
or anything similar evaluating to true. aString's value will remain "one\r2" until you change it. It's up to the console or alert that is displaying the string to choose how to render \r.
There are string processing methods in JavaScript for splitting and recombining strings (see the w3schools Javascript String Reference or Mozilla's String reference) that would better suit your purposes. If you start using characters like \r or \b in other languages and/or environments you're going to encounter different behaviors based on a whole host of factors.

"illegal character" error when Watir execute_script

I am fetching JavaScript code through a textarea in the User Interface and then executing the code in my app like this:
User input:
text = 'I am fine!!! ';
return text.replace(/(.+)\s+$/g, '$1’);
However, in rails, escape character get added to the user input in the textarea:
"text = 'hello how are you? ';\\d\r\nreturn text.replace(/(.+)\\s+$/g, '$1’);"
So the execute_script statement gives an 'illegal character' error.
browser.execute_script("text = 'hello how are you? ';\\d\r\nreturn text.replace(/(.+)\\s+$/g, '$1’);")
How can I get rid of escape characters without using regex so that execute_script runs fine?
Check this out:
browser.execute_script("text = 'hello how are you? '; return text.replace(/(.+)\\s+$/g, '$1');")
BUT! Why on Earth do you need it?
It is a very strange case and I am adding +1 to Dave's comment. It is not a typical user action to do some javascript magic. Try to think again about what are you doing.
Have you considered trying String#gsub! for this?
Here is how I might have approached it:
test = "\\d\r\nreturn text.replace(/(.+)\\s+$/g, '$1’);"
=> "\\d\r\nreturn text.replace(/(.+)\\s+$/g, '$1’)"
test.gsub!(/[\d\n\r\\d]/, '')
=> "return text.replace(/(.+)s+$/"
If you don't want to overwrite it, you could also use String#gsub, to return a modified copy
test.gsub(/[\d\n\r\\d]/, '')
=> "return text.replace(/(.+)s+$/"
You can obviously customize the regex to customize your need. Also be careful with smart quotes like the closing quotation mark for $1 as ’ is not the same as '

Line breaks in a YAML file

I'm using javascript to write a YAML file, but it's invalid.
I'm writing it with one string using \n line breaks:
'dir: ./_data/'+language+'\npath: '+options.path+'\nname: work'
My question is, is this the correct way to break between the vars in a YAML file? It does not seem to validate.
It is difficult to say without knowing what the language and options.path variables are.
This:
dir: ./_data/some_language
path: some_options.path
name: work
is valid YAML, even if you don't have a newline at the end of the file (I recommend to put a \n at the end of your string).
However if the variable options.path starts with a * you'll get an error about an undefined alias. If that value has : (colon + space) in it you'll get an error as well (mapping values not allowed).
You will also get an error if there are spaces before the first key (dir).
So it could generate correct YAML, but it might generate invalid YAML, depending on the values of the variables. The line breaks however, are at the right place.

Categories