Coffeescript: replace an <img> src attribute - javascript

I am new to coffee script and my end goal is to change the value of src in image tag to a different one.
the input will be a string.
lets say
string x = '<div class="sample">
<img src="/i/java.png">
</div>
<div class="sample">
<img src="/i/python.png">
</div>'
I want to replace the contents of src to something else.
I tried with the regex to try it out but it does not work.
Any idea on how do i achieve this. I used this regex.
s.replace /[/"][//]{1}i[//]{1}/g, '"//cdn.example.com/'
i am using my local application as well as this website to test my code

I believe there is a problem with your original regex.
Give this example a try,
x = '<div class="sample">
<img src="/i/java.png">
</div>
<div class="sample">
<img src="/i/python.png">
</div>'
console.log(x.replace /\/i\/[a-zA-Z1-9]+.png/g, '"//cdn.example.com/')
The regex /\/i\/[a-zA-Z1-9]+.png/g should match any values with the format of /i/anything_here.png, but ensures that the anything_here value contains at least 1 character (so /i/.png won't match).
If your string might contain more subpaths before the .png filename, use the following regex - \/i(\/[a-zA-Z1-9]+)+.png
This regex will allow as many occurrences of /anything before the /filename.png.

Related

PHP echo not producing correct result, turning string lowercase

I'm trying to echo a dynamic a tag which calls a javascript function, but the parameters are not being echoed correctly. They should retain their capitalization and not add spacing. Why is it doing this?
I've tried removing variables and just echoing a straight string with what I want, but it still displays incorrectly.
What I need:
echo '<img src="'.$info[1].'"/>'
Pure String Version:
echo '<img src="/images/calc-eng-desktop.png">'
Outputs:
<a href="/calc" onclick="redirTrackCalcBtn(" test_button_1",="" "="" calc")"="">
<img src="/images/calc-eng-desktop.png">
</a>
Should Output:
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
I also tried:
echo "<img src=\"".$info[1]."\"/>";
But that still outputs:
<img src="/images/calc.png">
as per Dharman's response I also Tried:
echo '<a href="'.$info[0].'"
onClick=\"redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\"
><img src="'.$info[1].'"/></a>'
This outputs:
<a href="/calc" onclick="\"redirTrackCalcBtn("Test_Banner_1"," "="" calc")\"="">
<img src="/images/preguntanos-h-es.png">
</a>
Edit for context:
It's for a dynamic banner within the content of a blog powered by WordPress.
You can simplify your expressions using the following technique ...
HTML accepts single quote or double quotes for attributes.
PHP can evaluate variables inside of double quote delimited strings. This can make your expressions much more easier to understand.
So based on this, the answer would be:
<?php
echo "<a href='{$info[0]}' onClick='redirTrackCalcBtn(\"{$bname}\", \"{$info[0]}\")'><img src='{$info[1]}'/></a>";
This will give the following result ...
<a href='/calc' onClick='redirTrackCalcBtn("test_button_1", "/calc")'><img src='/images/calc-eng-desktop.png'/></a>
In your question, you have shown an Pure String Version and what you thought was a normal output. Both of those outputs are wrong. You cannot use something like onclick="redirTrackCalcBtn("Test_Button_1", "/calc")" because the double quote right after the opening parenthesis finishes the onclick attribute which become onclick="redirTrackCalcBtn(". After that, the browser will try its best to find the following attributes and their values. So the spaces that you are seeing are just the natural space between attributes.
In conclusion, there is nothing wrong with echo.
You need to escape one set of the double-quotes, otherwise they are mixed together. Since you went for single-quotes in PHP, you need to use double in HTML/JavaScript and then use single-quotes again, but this time escaped from PHP.
echo '<a href="'.$info[0].'" onClick="redirTrackCalcBtn(\''.$bname.'\', \''.$info[0].'\')" ><img src="'.$info[1].'"/></a>';
The JavaScript variables are enclosed within \'
or
echo '<a href="'.$info[0].'" onClick=\'redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\' ><img src="'.$info[1].'"/></a>';
The onlick part is now enclosed with escaped quotes, everything else stayed the same.
You have 3 languages mixed together, 3 layers:
PHP will use '
-->HTML will use "
---->JavaScript will use \'
Each one uses double or single quotes and you only have two to choose from. Therefore you need to escape one of them.
A simpler example:
echo '<a onclick="alert(\'hi\')">Hello</a>';
Perhaps a simpler way to overcome quote escaping confusion is to assign the string in a different way. You can remove one layer of quotation by using heredoc notation.
as an aside, your "correct" output is not correct:
onclick="redirTrackCalBtn("Test_Button_1, "/calc")">
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
Your HTML should look like this:
<a href="/calc" onclick="redirTrackCalcBtn('Test_Button_1', '/calc')">
<img src="/images/calc-eng-desktop.png">
</a>
Using Heredoc notation, you don't have to concatenate and escape, just write it out the way the HTML should be:
$link =<<<LINKINFORMATION
<a href="{$info[0]}" onclick="redirTrackCalcBtn('{$bname}', '{$info[0]}')">
<img src="/images/calc-eng-desktop.png">
</a>
LINKINFORMATION;
echo $link;

find and append string [duplicate]

This question already has answers here:
RegEx match open tags except XHTML self-contained tags
(35 answers)
Closed 6 years ago.
Edit: the proposed question/answer does not solve my problem: Let me rephrase: find the string between <img src="and " />" and replace it with the original plus another string like ?w=500. I thought this might be doable with regex, but I'd be happy to do it in any JS way also. I don't have jQuery in this context though....
Let's say I have a string containing some markup with image tags, among other things, like this:
<img src="supercool.jpg" />
<p>very cool</p>
<img src="mega.jpg" />
How can I, with regex or otherwise, append a given string (say ?w=500) to each src attribute, so that I end up with
<img src="supercool.jpg?w=500" />
<p>very cool</p>
<img src="mega.jpg?w=500" />
I've looked at similar questions on SO but haven't been able to devise a solution, my regex skills are just too poor:)
I am sharing some PHP code using string replace may be this can help you.
Take all your code in a variable with single quotes and than replace jpg with .jpg?w=500. and set header with plain text.
echo str_replace(".jpg",".jpg?w=500",$a);
RegEx has no understanding of elements or attributes, so the following regex is highly fragile. It only looks for src="" and appends a given string to whatever is between the quotes. For a one-off script this should be enough. For anything more sophisticated use a proper HTML parser like SAX or DOM.
var in = '<img src="asd.png" /> <img src="ddd.jpeg" />';
var out = in.replace(/src=\"(.*?)\"/g, "src=\"$1?w=500\"");
out:
<img src="asd.png?w=500" /> <img src="ddd.jpeg?w=500" />
In case you're trying to do this in a browser (you didn't specify), you want something like this (jQuery):
$("img[src]").each(function() {
this.src = this.src + "?w=500";
});
Based in this #Gumbo answer and assuming the string you are giving, that img tag doesn't have any extra attribute before src you can apply this RegEx.
let str = '<img src="supercool.jpg" /><p>very cool</p><img src="mega.jpg" />';
let res = str.replace(/<img src="(?:[^"\/]*\/)*([^"]+)"/g, '<img src="$1?w=500"');
console.log(res);
If you don't need any extra considerations your question looks more like a duplicate of the one I linked to you.
For very simple cases you can use a reg exp to match basic HTML, but once it gets complex, reg exp are a bad idea. Sometimes you need to clean up some code and it works fine.
With your case, your html structure is simple so you can make a match.
var txt = document.getElementById("in").value;
var result = txt.replace(/(<img.*\ssrc=['"])([^'"]+)/g, function(m, l, s){
return m + (s.indexOf("?")!=-1 ? "&" : "?") + "w=500";
});
document.getElementById("out").value = result;
<textarea id="in" rows="4" cols="50">
<img src="supercool.jpg" />
<p>very cool</p>
<img src="mega.jpg?foo=bar" />
<img alt="boo" src="mega.jpg" />
</textarea>
<textarea id="out" rows="4" cols="50"></textarea>
but it can be broken very easy.... You are better off creating a DOM fragment, working with the DOM and changing the attributes. The problem with the DOM solution is it will try to load the images, which is what I think you are trying to avoid in the first place.

Find a character and insert line break

How might I go about finding a specific character and inserting a line break using jQuery?
The character I need to find is a hyphen - and its always within a product title on an ecommerce site and takes the following format:
This is a title - This is the colour
How can I find the dash for every product title and insert a line break to for the colour name on to a separate line?
The exact HTML markup I'm using is as follows:
<a href="#" class="product c-3">
<div class="product-thumb">
<!-- Other code is in here / Removed for brevity -->
<div class="product-title">
This is a title - This is the colour
</div>
</div>
</a>
You can use replace to find a - in the element's HTML and replace it with -<br />. Try this:
$('.product-title').html(function(i, v) {
return v.replace('-', '-<br />');
});
You can replace with simply '<br />' if you want to remove the hyphen completely.
Example fiddle
Update: This can now be made even more succinct by using an arrow function:
$('.product-title').html((i, v) => v.replace('-', '-<br />'));
Try:
$('.product-title').each(function() {
var self = $(this);
self.html(self.html().replace(/-/, '-<br/>'));
});

impossible to escape single quotes in XML

please help me with this issue. I have a php file which generates XML. I have the following code that I can not escape a JS script within XML as follows:
$xml_after='<html>'.htmlspecialchars('
<div class="options" id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'\',hide_element(\'confirmation\');\''.$lang['delete'].'\',remove_table(\''.$tables_row['id'].'\');hide_element(\'confirmation\');\');return false;\" ><img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
The problem is in onclick functions..
Please help, full day losted already , thank you
Be aware that htmlspecialchars() escapes < and >, too. You have to use it on each value separately, not on the complete html fragment.
htmlspecialchars() has an option that escapes all quotes.
var_dump(htmlspecialchars("Escaping: <>&'\"", ENT_QUOTES));
Ouptut:
string(35) "Escaping: <>&'""
But it would be better to use DOM and let it take care of the escaping.
Additionally, I suggest using data-* attributes in HTML. The Javascript can read the attributes and bind the logic to the elements. This separates the actual JS logic from the HTML.
I think your code is incorrectly formatted
$xml_after='<html>'.htmlspecialchars('<div class="options"
id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="
show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'
\', hide_element(\'confirmation\');\''.$lang['delete'].'
\', remove_table(\''.$tables_row['id'].'\');
hide_element(\'confirmation
\');
\');return false;\" >
<img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
after each of the functions inside the show_confirmation functions you have a ; which isn't valid in a function calls parameter list
On the last line of the onClick function:
\');\');return false;\" >
The second \' is unmatched and the double quote \" shouldn't be escaped as far as I can see change that and maybe it will work for you.

Regexp for content inside tags

I use Javascript
I have this:
<(div|span) class="search-result-(body-text|title)">(.*?)</(span|div)>
And i use is on this content:
<div class="search-result-item club">
<span class="search-result-type">Projekt</span
<span class="search-result-title">Titel</span>
<div class="search-result-body-text">
Body text
</div>
<div class="search-result-attributes">
<span class="search-result-attribute">Attribute</span>
</div>
</div>
My result is:
<span class="search-result-title">Titel</span>,
<div class="search-result-body-text">
Body text
</div>
Thats make sense, but how should my regexp look like so it strips the tags, so i only get: Titel, Body text
It is required by law that someone post a link to this: RegEx match open tags except XHTML self-contained tags which you should read and reconsider whether you really want to be parsing HTML using regular expressions.
However, what you want is the contents of the third () group in your match. The exec method of a JS regular expression object is an array containing the whole match at index 0, and the matches from all the groups at indices 1,2,... (in this case index 3 is what you need).
[NOTE: an earlier version of this answer had "first" and "1" instead of "third" and "3" above, because I misread your regexp. Sorry.]

Categories