This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 1 year ago.
I have been trying to get a regex working where I can check whether the naming scheme of an ID follows the correct format. But I want to be able to change the format using a variable. The regex combination itself works, but as soon as I tried to add in a variable, it seems to stop functioning. This version seems to work:
const id = $("#div-1-name-1").attr("id");
const regex = new RegExp(/^div-\d-name-\d$/);
console.log(regex.test(id)); // returns true as expected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="div-1-name-1"></div>
But as soon as I want to make "name" a variable, so I can interchange this using a function later on, it seems to stop working. For some reason, it always seems to return false.
const id = $("#div-1-name-1").attr("id");
const variableName = "name";
const regex = new RegExp(`/^div-\d-${variableName}-\d$/`);
console.log(regex.test(id)); // returns false, where true expected
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="div-1-name-1"></div>
Am I perhaps inserting the variable in a wrong way? I cannot seem to figure it out.
You need to escape the regex string and remove the/ from the start and the end like this:
new RegExp(`^div-\\d-${variableName}-\\d$`);
Or as Wiktor commented
new RegExp(String.raw`^div-\d-${variableName}-\d$`);
Related
This question already has answers here:
Template literal inside of the RegEx
(2 answers)
Closed 1 year ago.
hi I am coding an online shop ,
currently working on add to cart functionality,
like to store product ids and their quantity in a cookie like this id1:qt1,id2:qt2...
like to check if a product is already is in cart , looks like my regular expr doesn't work
const reg = new RegExp(`${product_id}:\d+`);
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
Yep, your regex is off :)
It stumped me for a second, but its clear when you check what your "regex" string actually evaluates to: /product_id:d+/. This is because the string you're passing in sees the \d as a literal d. To fix this, just throw another \ in there so the original \ is whats being escaped. Before, you were matching things like "apple:ddddddd".
Once you do that, your code DOES seem to work, but maybe just not like you expect it to?
I've put your code into a function, since you would -- presumably -- be calling this every time you want to add an item to the cart, and added a console.log statement to show the end value of the "cookie."
// Just as a stand in for actual values
let cart_cookie = 'apples:2,oranges:3,bananas:1';
function addCartItem(product_id) {
const reg = new RegExp(`${product_id}:\\d+`);
console.log(reg)
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
console.log('cart_cookie is now ', values.join(','));
setCookie('cart', values.join(','), 7);
}
else {
console.log('already in cart.')
}
}
addCartItem('apples');
// already in cart.
addCartItem('kiwis');
// cart_cookie is now apples:2,oranges:3,bananas:1,kiwis:1
Its fixed! 🥳 But...
I'm not quite sure what your product ids look like, but if they contain special characters (e.g. periods, question marks, etc.) it'll cause some issues with how your regex performs. I doubt you have things like question marks in it, but something like this illustrates my point:
let cart_cookie = '123.15:3,2.5.141:1';
/* ... */
addCartItem('1.3.15');
// already in cart.
I know, its a rather unlikely scenario -- and it might not even apply to you if you know your product ids won't contain anything tricky -- but if you're goal is to build an online shop, you'll probably want to cover all your bases.
Even fixing that, this still has a potential issue, as this will only let you add a quantity of 1 to an item thats not already in the cart, with no ability to increment it after that. Not sure if thats what you're going for.
This veers off of the main question you posed, but a potentially better solution might be using the browser's localstorage (or sessionstorage) to keep track of the cart. This would allow you to use more familiar data structures to store this info, rather than a string that you have to pray you're parsing correctly.
More info on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
you can use just array method instead you don't need for regex for that,
for example..
const values = cart_cookie.split(',');
values.foreach(value => {
if(value != product_id){
values.push(`${product_id}:1`);
setCookie('cart', values.join(','), 7);
}
});
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()
This question already has answers here:
Remove first character from a string if it is a comma
(4 answers)
Closed 3 years ago.
My website uses product references in this style: "R202020"
I want them to be shown like this for the users of my website: "BA2202020"
So basically I'm looking for a script, which formats the style of my reference numbers (should affect a ".reference" class I've created) by:
Removing the "R" in the original reference - replacing it with a "BA2" in stead - leaving the rest as it is (the "202020" part).
How can I do this?
Find 1st character of your string using string[0] and replace that with your desire value like below.
var string=$('.YourClass').text();
var result = string.replace(string[0],'BA2');
$('.YourClass').text(result);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='YourClass'>R202020</span>
Try replace method. https://www.w3schools.com/jsref/jsref_replace.asp
'R202020'.replace('R2','BA2') // BA202020
I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.
The currency string is captured here, in part of an "each" loop:
var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();
The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:
var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));
However with that last line in place, the script will not run.
If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.
if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.
I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.
I'm really stumped. Help??!! Thank you!!!
i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.
var id = element.name.replace ( /[^\d.]/g, '' );
element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22).
hope it can help you. :)
This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
I have written a simple code in a .js file (in Zend framework, but I dont think it matters)
var location = "localhost:8080/mymodule/id/1#";
location.replace(/\#/g, "");
alert(location.valueOf());
return;
but I dont know why I can not see the result I want.
I get my page url and want to omit all number signs appears in it. but the code above does nothing.
please help
location is a bad name to use for a variable since it collides with the window.location variable used for the actual browser page location.
If you change location to loc in your above code, and then also add loc = in front of the loc.replace() call (since replace() doesn't modify the input, but instead returns the new version), your code works.
replace will not change the value of the original string, you need to assign the result to a new variable -
var newString = location.replace(/#/g, "");
alert(newString);
Demo - http://jsfiddle.net/5H5uZ/
It can be done in one line. This is the result you look for?
alert("localhost:8080/mymodule/id/1#".replace(/#/g,''));
//=> alerts 'localhost:8080/mymodule/id/1'