I started learning JavaScript last week, I saw this code yesterday and I did some research about it, but now I can't figure what it does:
var y=document.forms['post'];
var x=y.message.value;
x=x.replace(/</gi,'(').replace(/\</gi,'(');
y.message.value=x;
This code grabs the value from an element named message in a form named post. It then replaces all < with ( and puts that value back into message.
It's sanitising HTML from text in a form element (an input, from the looks of it), by replacing all < with (...
...and then doing it again; it probably means to then replace all > with ) for better readability.
Here is my understanding of it:
Variable y holds your form which has name = post.
Variable x holds value property of tag message.
Replace < and put ( in message.
Assign new message tag x to original y
After the first line, y has a reference to the document's form with name="post".
After the second, x has the contents of the field with name="message".
The third line uses regular expressions to replace every left angle bracket with a left parenthesis, and the second does the same for left angle brackets preceded with a backslash. It seems redundant because < has no special meaning in regular expressions; the "i" modifier is also useless in this case.
The last line assigns the modifed message back to the form.
This code is supposed to prevent injecting HTML elements into the "message" field, but does this in a rather crude way.
Related
I cant use send_Keys() method to input values in the current website im working on.
So im trying to use javascript to input values.
i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.
i use the javascript code to input value below
driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")
and it worked.
But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?
Here is the code that i tried
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")
I know its wrong, any help would be appreciated. My Javascript is weak.
Just some side note if anybody would be able to solve my send_keys() error.
The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-
First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).
The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"
If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.
In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:
import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")
That outputs:
document.getElementById('CustCd').value = "J590";
Live Example
That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).
It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:
import json
class Example:
foo = ""
bar = 0
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")
That outputs:
const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;
obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.
Live Example
You need to insert the variable as variable, not literal
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")
Using Javascript to input the values of a variable you can use the following solution:
ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")
An example, to input the values of a variable within Search Box of Google Home Page:
Code Block:
driver.get("https://www.google.com/")
value = 'J590'
driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")
Browser Snapshot:
You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()
Here is the source code of the page.
The line that has the value that I want to grab is at line 194 exactly.
Here is a regex demo, but it returned undefined and I can't fix it
by var test = getObj\("Frm_Logintoken"\).value = "(.*)"; console.log(test[1]);
And this one too, gave me: undefined.
If there only was a way to do this:
/getObj\("Frm_Logintoken"\).value = "(.*)";/g.exec('getObj("Frm_Logintoken").value = ?
There is a question mark, because I don't know its value, and if the code can replace the question mark with the value of that value from line 194, that would be great.
Not the value is a page generated value
You can use str.match(regex)[value_index] to extract mached values from regx (the values inside parenthesis in regular expression will be extracted).
in your case:
str.match(/getObj\("Frm_Logintoken"\).value = "(.*)";/)[1]
here is a working example: codepen
I have two HTML elements that are alternatives of each other and I am trying to write a JS function that removes one if the other is present (they originated as words within <sic> and <corr> beneath <choice> in a TEI document). In my transformation, they are both assigned a code (not an #id: #id is randomly generated and has to remain so for other purposes) with a unique prefix:
<a id="abc" choicePOS="sic0">Element1</a>
<a id="xyz" choicePOS="corr0">Element2</a>
In a JS function that 'belongs' to Element1, I want to select Element2 so as to remove it. This is what I have tried (el is element1):
var choicePOS = el.getAttribute("choicePOS").slice(3); // produces 0
var corrID = "corr" + choicePOS; // produces corr0
var corr = document.querySelectorAll("a[choicePOS=corrID]");
This fails, presumably because the corrID variable in the last line is in quote marks and is being taken as a string. I have read various tutorials on CSS selectors and can't find any guidance on how to use them with a variable attribute value. Is this possible? If so, how? If not, any alternatives?
EDIT: A number of other questions relating how to concatenate strings with variables in JS have been suggested as duplicates of this one. To clarify, I am asking specifically about querySelectorAll, as I cannot find any examples this being used with variables. If the answer is that its selector is to be treated as any other JS string (i.e. variables can be concatenated in), then that is perfectly satisfactory.
Use template literals to evaluate that
var corr = document.querySelectorAll(`a[choicePOS=${corrID}]`);
I have an equation/formula stored in database and I want it to be triggered based on key up input event in a webpage.
Example formula: [55-57]
This is a simple minus operation, where the number actually represents the id of a row in database
I have looked at this solution which replaces numbers found in a string to new value. But I need the new value to be replaced with incremented letters such as a, b and so on. Also the leading and ending brackets [] need to be removed so that I can perform an eval later using JavaScript.
Later the equation will be convert to a-b. Variable a and b represent other HTML elements that holds a value. So whenever I key in something into text field, changes will reflect on other part of webpage. It's like auto computation.
Thank you for those helping this. Hope this question will help somebody.
Try something like this. If you need more help, you seriously need to re-word your question or post a jsfiddle, or something.
var eqn = '55-57'; // brackets removed. Remove them with a regex of /\[|\]/g if you need to
var result = eval( eqn.replace( /\w+/g, function( res ){
return +document.getElementById( res[1] );
} );
Basically this replaces 55 and 57 with the numerical values of #55 and #57. It would also work for #b, etc.
It then eval's the result, basically doing whatever math is in your equation.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode(" , /n , "+this.prime.nextPrime()));
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Okay so this is my code I am displaying an array of prime numbers. The issue is that I want each prime number to be on a seperate line but I am unable to do this. I have tried /n and but they have not worked. It is being displayed in a textarea in html. Thank you
You could append a br element:
primes.appendChild(document.createElement('br'));
...although usually the way you'd want to do this would be to put the primes in some kind of element container that you could style appropriately with CSS. A series of divs would automatically stack vertically:
var div = document.createElement('div');
div.appendChild(document.createTextNode(/*...your prime...*/));
primes.appendChild(div);
Two side notes on this line:
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
First, it's almost always best to use function references, not strings, with setTimeout. So:
calcPrimesDelay = setTimeout(calcPrimesLoop, this.delay);
Second, unless you're declaring calcPrimesDelay somewhere you haven't shown, you're falling prey to The Horror of Implicit Globals.
You should use a backslash instead of a forward slash (\n)
EDIT: The below only applies to "normal" elements. For a textarea, you should be doing primes.value += " , \n , "+this.prime.nextPrime();
Additionally, newlines are collapsed in HTML (if you write text on multiple lines in your source code, it comes out on one line) but you can "fix" this using simple CSS:
primes.style.whiteSpace = "pre-wrap";
Spread the word about white-space! People need to stop using <br /> tags just to get a newline!