This question already has answers here:
How do I replace all occurrences of "/" in a string with "_" in JavaScript?
(4 answers)
Closed 8 years ago.
String contents :
background:url(abcd.gif); background:url(images/header2.gif) no-repeat;
background:url(images/bullet1.gif) no-repeat 11px 13px;
Javascript Code :
var testRE = originalcode.match("url\(\(.*)\)");
testRE = testRE[2].replace('(','');
testRE = testRE.split(')')[0];
var img_path = "http://xyz.com/800002418/"+testRE;
originalcode = originalcode.replace(testRE,img_path);
In the above code it's only replacing first instance of match. I am trying to replace multiple instances for url in string like above are 3 instances in string for url. But it's only replacing 1st instance and that is "abcd.gif" to "http://xyz.com/800002418/abcd.gif". And rest is as it is.
I suspect what you're actually trying to do here is as follows:
originalcode = originalcode.replace(/url\(([^\)]*)\)/g, "url(http://xyz.com/800002418/$1)");
See #Phylogenesis's answer for how to do what you seem to think you want to do, but is that what you really want to do? After you've modified the string, what are you going to do with it? I suppose perhaps you're going to set it as the string CSS value on some element, as in elt.cssText=. But why do you think three background properties in a row are going to do anything useful? Each one will just override the previous one.
Taking a step back, instead of trying to manipulate CSS declarations as strings using regexp's, I suggest manipulating individual property values. So, something like
foo.style.backgroundImage=foo.style.backgroundImage
.replace(/\(.*)\)/,"http://..."+$1);
But I'm still confused as to why you would want to do this. I guess it's because the remote URL is only known at run-time? The most flexible solution is to place a CSS file on the host in question and load it. If the images are there, you ought to be able to arrange to put a CSS file there along with them. The URL references in the background property values will then automatically be interpreted in terms of the URL of the CSS file, without having to rewrite in this ugly fashion.
Related
This question already has answers here:
CSS class starting with number is not getting applied
(3 answers)
Closed 2 years ago.
Basically I'm gonna update this class' html but I keep getting the same error and have absolutely no idea why
document.querySelector(`.${clickField}`).innerHTML = `<img src ='${icon}.svg'>`
Uncaught DOMException: Document.querySelector: '.3-1' is not a valid selector
(I've seen similar questions but they all have jquery etc so i didnt understand shit from them)
Someone just said classes cant start w numbers he's right im so dumb lmfao
image of 3-1 existing in DOM
I'm assuming clickField is supposed to be the class of the element you want to get. In that case, since the class starts with a digit, the easiest way to select it using CSS selector is using attribute selectors, like so:
document.querySelector(`[class="${clickField}"]`).innerHTML = `<img src ='${icon}.svg'>`
If clickField might contain " characters, you need to replace ${clickField} by ${clickField.replace(/"/g, '\\"')} to escape them properly.
There is also a far easier way, using document.getElementsByClassName():
document.getElementsByClassName(clickField)[0].innerHTML = `<img src ='${icon}.svg'>`
Classes may contain any characters except space, as the HTML standard imposes no restrictions on them.
This question already has answers here:
Create RegExps on the fly using string variables
(6 answers)
Closed 5 years ago.
I'm trying to pass an object to the MongoClient collection.find() method but I don't want quotes around the values. If I pass a literal it works as expected:
cursor = collection.find({EmployeeName: {'$regex': /Jo/i}});
However, if I try and build that object like:
var queryt = "/Jo/i";
var queryo = {
EmployeeName: {'$regex': queryt}
};
It doesn't work. If I do a console.log(queryo) I can see that there are quotes around the "Jo/i":
{ EmployeeName: { '$regex': '/Jo/i' } }
Note that in my application queryt is actually being set by extracting values from the 'query' object that is returned from a 'get' function from express. For example, I am calling the webpage with an ending URL of "?EmployeeName:/Jo/i". In my "get" function I am doing:
var queryt=req.query.EmployeeName;
So, basically I'm trying to use this node.js app to be a back end server, accepting queries via http get requests.
I've tried various methods of striping the quotes but with no success.
I'm sorry if this is a newbie type question, but I am just learning, and have already spent hours trying to work around it. I'm hoping some more seasoned node.js developer can quickly tell me how to construct this object so collection.find will accept it. Thanks!
Remove double quotes in var queryt = "/Jo/i"; this will create string.
it should be var queryt = /Jo/i; this will create regular expression
Update: kcantrel found answer. above method will not work. below method works for him.
queryt = RegExp("jo", "i")
This question already has answers here:
How to use JavaScript variables in jQuery selectors?
(6 answers)
Closed 7 years ago.
I searched high and low now but I can't figure out how to get this to work:
I need to get the element whose class name contains a number that I pass with a variable.
For better understanding: This is inside a "click" event on a gallery. Whenever an img is clicked I search for the src, see which number the string contains and then want to find the matching p whose class contains the same number. So I can manipulate the matching text to the picture that is currently displayed (Since the plugin I use strips away any id or class I can only identifiy a picture by its source name).
So far it does work if I directly put the number in as a String. Like this:
var team_t = $(this).find("img").attr("src");
for(n = 1; n <=6; n++ ){
if(team_t.indexOf(n) != -1)
{
$('#text_content').find("p[class*='3']").css("background-color", "red");
}
}
But instead of "3" I want it to get the number that the variable n holds. I tried this but it did not work:
$('#text_content').find("p[class*=' + n + ']").css("background-color", "red");
Actually it didn't work with any kind of variable I tried to pass. I also saw and tried examples that use contains( ) or hasClass( ) and others.. but nothing worked for me. I'm not extremly familiar with the syntax though.
How do I have to write this so it takes the variabel as a string?
If I do alert( n ) it shows the correct number, so that's not the problem.
You were on the right track with string concatenation, you just didn't get all the way outside the string:
$('#text_content').find("p[class*='" + n + "']").css("background-color", "red");
// Change is here -----------------^- and -^
In your attempt, the + n + was still in the outer quotes, and so was used literally in the selector (making it fail).
That said, if you have any control over the DOM structure (but it sounds like you may not), there's probably a better way. For instance, you could put a data-* attribute on the element that gives an appropriate selector for the p element (possibly even by id, but that's just one option).
You might also want to end the loop once you've found the index, by putting break; on the line after the line setting the red color.
Finally: You might want to use a class to add the red color rather than mixing your presentation into your JavaScript code.
I'm fairly new to any kind of language but I need to modify a code at my work because the guy doing it previously left and no replacement.
I basically would like to put in a variable a specific part of a url.
The URLs look like this:
http://www.test.com/abc/hhhhhh/a458/example
I need to extract the a458 part and put it in a variable. This part is always at the same place but can be of variable length.
The URLs always have the same structure. I tried /hhhhhh\/{1}[a-z0-9]+\/{1}/g but it doesn't fully work. It keeps the hhh and the /.
no need for regex, just split it
var link = "http://www.test.com/abc/hhhhhh/a458/example";
var linkParts = link.split("/");
//If the link is always in that format then a458 or whatever
//would replace it will be in index 5
console.log(linkParts[5]);
This question already has answers here:
RegEx match open tags except XHTML self-contained tags
(35 answers)
Closed 8 years ago.
I have this piece of HTML code:
<tr class="AttCardFooter" onMouseOver="this.style.backgroundColor='#E1EAFE'" onMouseOut="this.style.backgroundColor='Transparent'">...etc etc.. new lines etc.. <td title="Saldo+">33:33</td><td title="Saldo-">22:22</td> .. etc etc...
I need JavaScript regex that will grab these two fields 33:33 and 22:22
All that I have tried fails because of new line characters.
If anyone knows how to accomplish that I would be very grateful.
Don't use a regexp. I guess your piece of html is an innerHTML or outerHTML of some element. Instead of parsing html with regexp do this:
var el = document.querySelector("tr.AttCardFooter"); // I guess you have that variable already
for (var i=0; i<el.cells.length; i++) {
var td = el.cells[i];
if (td.title == "Saldo+")
var positiveSaldo = td.innerText;
else if (td.title == "Saldo-")
var negativeSaldo = td.innerText;
}
alert("Voila:\n"+positiveSaldo+"\n"+negativeSaldo);
You may improve this with your favorite libraries dom functions. For example in jQuery it would be something like
var el = $("tr.AttCardFooter");
var positiveSaldo = el.find('td[title="Saldo+"]').text();
var negativeSaldo = el.find('td[title="Saldo-"]').text();
You would have to process the new line characters. Try this:
Pattern p = Pattern.compile(myRegExp, Pattern.DOT_ALL);
Try this lib and add /s flag so the dot matches new lines.
http://xregexp.com/
Regular expressions cannot parse HTML.
If the table row is already part of your document, then there's no need to do anything fancy. Use the DOM to extract the values you need -- Bergi has great suggestions.
If the string comes from somewhere else, consider using a hidden <div> and set its innerHTML. The browser handles parsing the string; you then use DOM methods to extract the values you need.
Of course, if that "somewhere else" is untrusted input (third party site, user input, etc), you can't just use a hidden <div> due to the security problems of blindly sticking potentially executable code into your page. Instead, you need to sandbox this step in an <iframe> running on a different Origin.