"illegal character" error when Watir execute_script - javascript

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 '

Related

JavaScript RegEx won't match with newline

I'm current making a simple application using NodeJS to translate input into a defined format. For this I'm using the following piece of JavaScript, where content is the input.
content = content.replace(/(.+)\n=+$/gm, '<div>$1</div>');
content = content.replace(/(.+)\n-+$/gm, '<p>$1</p>');
Using this, I would expect the code below
Message
======
Another Message
------
translate into
<div>Message</div>
<p>Another Message</p>
However, I get the same output as input (so nothing changed),
I tried it with both RegExr and WebStorm's RegEx tester, and both of those find a match. When I log the result of content.match(/(.+)\n=+$/gm) I get null.
When I remove the \n from the RegEx and the input, it does seem to match, which has me think the \n is causing some kind of issue. However, I'm not aware of any issue this could be causing.
are you using windows?
give a try to:
content = content.replace(/(.+)\r\n=+$/gm, '<div>$1</div>');
content = content.replace(/(.+)\r\n-+$/gm, '<p>$1</p>');
depending on OS and browser you may get there \n or \r\n (\r denotes carriage return, they may be other reasons for them to appear. But in your regex you should expect either \n or \r\n
Edit:
As suggested by Poul Bak you could simply add ? after \r to handle both cases:
content = content.replace(/(.+)\r?\n=+$/gm, '<div>$1</div>');
content = content.replace(/(.+)\r?\n-+$/gm, '<p>$1</p>');

How to allow user to input escaped chars in Javascript

A simple one here.
I have an HTML <textarea> in which I want to allow the user to enter escape sequence. I.e.:
Hello\nworld\x21
And I want my script to "interpret" the \n and the \x21 to get:
Hello
world!
Thanks
EDIT:
The purpose of this is to allow the user to enter thermal printer's code in an html page. The printer needs special chars. I want to take that string, "interpret" the special codes and send it to the printer. Currently, the printer prints the string as-is.
The only way I can think of that doesn't use a long replace line is with the eval() function. You could, for example, use the following:
function useEscapes(s) {
return eval('("' + s.replace(/([^\\]|^)(?=(\\\\)*["\n])/g, '$1\\').replace(/\n/g, 'n') + '")');
}
The replace is to make sure it's safe to pass into the eval() function.
EDIT 9/28/2016:
There's a better way that isn't a security risk. Because a string literal is valid JSON, you can wrap it in quotes and use JSON.parse. You can also possibly escape quotes in it so that users don't get inexplicable syntax errors. If an attacker tries to put code outside the string, it will just throw a syntax error.
function useEscapes(s) {
return JSON.parse('"' + s
.replace(/((^|[^\\])(\\\\)*)"/g, '$1\\\\"') // optional - prevents syntax errors
+ '"');
}

Remove new line in javascript code in string

I have a string with a line-break in the source code of a javascript file, as in:
var str = 'new
line';
Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.
Thanks in advance!
EDIT (2021)
This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.
What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.
However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.
The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:
var str = `new
line`;
is totaly valid and would be identical to
var str = 'new\n line';
As far as removing the newlines goes, I think the answers below address that issue adequately.
If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');
str = str.replace(/\n|\r/g,'');
Replaces all instances of \n or \r in a string with an empty string.

Using script to find string of text up until first html tag

I have a service that is returning a message. That message may be a combination of plain text or an html formatted text.
ex1: "This is a message"
ex2: "<p> This is also a message <p/>"
ex3: "This is also a <strong> message </strong>"
The thing we would like to do is come up with a script that would return as much plain text up until the first tag. So in the examples above:
would return "This is a message.
would return ""
would return "This is also a"
I am not sure what approach is the best to do this. Can i accomplish this using Regex or JS. I know Regex can easily return text between two tags, but what i am looking for is a little different. Thanks in advance for any advice or help.
The simplest solution would be to match anything except <s, starting at the beginning of the string:
match = subject.match(/^[^<]*/)[0];
This fails if <s could occur in comments/quoted strings before the first HTML tag, but that might not be a problem.
Test on JSFiddle
Explanation:
^ # Anchor the match to the start of the string.
[^<] # Match any character that's not a <
* # zero or more times (as many as possible).

Javascript regex problems around \n

I have a text pattern that I am trying to replace in a node.js application. The pattern is:
***
some text
***
It is created in javascript with the following code:
var textblock = "***" + '\n' + 'some text' + '\n' + "***" + 'the rest of the text block'
The following regular expression works in regexpal and seems correct to me:
\*{3}\n.+\n\*{3}
But when I put it in my javascript code, it fails:
textblock.match(/\*{3}\n.+\n\*{3}/) // returns null
I tested, and even just *{3}\n doesn't seem to work. Am I missing something idiosyncratic about how javascript handles \n ? I've tried /m as well, and I've also tried [\n\r].
Thanks!
UPDATE: turns out that the GitHub API markdown processes issue body text and eliminates newlines. So my regex was correct, but I was wrong about the text I was matching in.
Try changing textblock to t:
var t = "***" + '\n' + 'some text' + '\n' + "***";
alert(t.match(/\*{1}\n.+\n\*{1}/));
(fiddle; removed some * from the regexp to check if it is working properly).
It might be an issue with line-endings. If you match for [\n\r] instead of just \n it works OK.
Here is a fiddle to demonstrate: http://jsfiddle.net/xD8a5/
The text I'm finding and replacing comes from a GitHub issue fetched via API. Turns out that when you put multiple asterisks in a row, they omit the newline chars before and after since they convert it into a graphical line.
The answer was to not require actual newline characters. This worked:
match(/\*{3}[\n\r]*.+[\n\r]*\*{3}/)
Thanks everyone for your help!
Use \\n instead of \n i tried on my code and it is working fine

Categories