find and append string [duplicate] - javascript

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.

Related

Coffeescript: replace an <img> src attribute

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.

How to replace all img tags in HTML string with <a><img></a>?

I have HTML string and I open it in UIWebView. Now, I want to make all my images clickable, to put them into link tags like:
Was:
<img src="..." />
Became:
<img src="..." />
Is there any easy solution?
I've tried to find all tags and replace them inside of the string, but it was very painful.
I've tried that:
let js = "var a=document.createElement('a');a.href='http://mylink.com';var image = document.getElementById('mydiv').getElementsByTagName('img')[0];b=a.appendChild(image);document.getElementById('mydiv').appendChild(a);"
self.webView.stringByEvaluatingJavaScriptFromString(js)
but it did not help me
Short answer: No, there is not an easy solution. Don't do that. Trying to parse and change HTML source from a client app is a horrible idea, and will always be very painful. It's kind of like trying to perform brain surgery on yourself with a sawzall, a mirror, and some old dental tools.

How do I pass a string from Javascript to the src part of an image tag in HTML?

I've written an extremely simple Javascript function. All it does is randomly selects an image filename (file.png, for example) and and passes it over with getElementById.
var nameA=fileNames[randnumA];
document.getElementByID("image1").firstChild.nodeValue= nameA;
Of course, there's other stuff to go along with that, but I didn't feel it necessary to be included. All I'm doing is passing a string over from Javascript. Simple enough.
The problem is that I want to use that string as the source for an HTML tag. I'm a noob, and haven't done this before, so a simple explanation would be awesome. My current code in HTML is this:
<img src=<span id="image1"> </span>>
I didn't expect it to work, as placing tags within other tags doesn't feel right.
Any ideas as to how I'm supposed to do this? Thanks everybody, I appreciate the help.
Also, the function is definitely being called. I have it as an onLoad in the <body> tag.
blank stare
<img id="image1" />
JS:
var nameA = fileNames[randnumA];
document.getElementById('image1').src = nameA;
Javascript:
var nameA=fileNames[randnumA];
document.getElementByID("image1").src = nameA;
HTML:
<img id="image1" />

How do I write the following as a regular expression to replace multiple occurances?

Background:
I have string of html with about 10 image tags that passes through some JavaScript as a string at runtime before being injected into a containing element. The data-thumb tag of each image is slightly incorrect and needs to be altered before making it into the DOM. Here is an example:
<img src="foo_lg_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_lg_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_lg_db.jpg" data-large="fizz_lg_db.jpg" />
Needs to become:
<img src="foo_tn_db.jpg" data-large="foo_lg_db.jpg" />
<img src="bar_tn_db.jpg" data-large="bar_lg_db.jpg" />
<img src="fizz_tn_db.jpg" data-large="fizz_lg_db.jpg" />
Question:
In JavaScript (jQuery is OK), how do I achieve this search and replace?
THE ANSWER:
Thanks to Mark's answer I learned that it is possible to instantiate a jQuery object before it hits the DOM so, rather than using regex, I did something like this:
var stringHtml = "<img . . .";
var div = $("<div>").html(stringHtml );
$.each(div.find('img[src]'), function () {
$(this).attr('src', $(this).attr('src').replace('_lg', ''));
});
return div.html();
$('img[data-thumb]').each(function() {
$(this).attr('data-thumb', $(this).attr('data-thumb').replace('_lg_','_tn_'));
});
Something like that in jQuery.
Sounds like a problem you should be fixing server-side if possible though.
If you give jQuery an HTML element like $('<div>') it will essentially create the HTML element for you and then you can manipulate it before inserting it into your DOM. I don't know if it will handle multiple elements, but you can create a container first (like above) and then set the content like so
$('<div>').html(yourHtml).find('img[data-thumb'])./* code above */

Javascript regexp replace of multiline content between two tags (including the tags)

In the string
some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/>
I need to remove
<p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/>
Can't find a way how to do it.
var id = 'item_1';
var patt=new RegExp("<p id='"+id+"'(.)*|([\S\s]*?)end_of_"+id+"'\/>","g");
var str="some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/>";
document.write(str.replace(patt,""));
The result is
some text for
<br>
remove
<p></p>
<br id="<p id=" class="item" clear="all" item_2'="">
another multiline content
<p></p>
<br id="end_of_item_2" clear="all">
Please help to solve this.
Here's the regex for the current scenario. When the regex approach eventually breaks, remember that we warned that parsing HTML with regex was a fool's errand. ;)
This:
var s = "some text <p id='item_1' class='item'>multiline content\r\n\r\n for <br/>remove</p><br clear='all' id='end_of_item_1'/><p id='item_2' class='item'>another multiline content\r\n\r\n</p><br clear='all' id='end_of_item_2'/><ul><li>";
var id = 'item_1';
var patt = new RegExp ("<p[^<>]*\\sid=['\"]" + id + "['\"](?:.|\\n|\\r)*<br[^<>]*\\sid=['\"]end_of_" + id + "['\"][^<>]*>", "ig")
var stripped = s.replace (patt, "");
Produces this:
"some text <p id='item_2' class='item'>another multiline content
</p><br clear='all' id='end_of_item_2'/><ul><li>"
Why can't you use the DOM API to remove it? (add everything to the document, and then remove what you don't need)
var item1 = document.getElementById('item_1'),
endOfItem1 = document.getElementById('end_of_item_1');
item1.parentNode.removeChild(item1);
endOfItem1.parentNode.removeChild(endOfItem1);
I need to assume a bit of unspoken constraints from your question, to get this to work:
Am I right in guessing, that you want a regex, that can find (and then replace) any 'p' tag with a specific id, up to a certain tag (like e.g. a 'br' tag) with an id of 'end_of_[firstid]'?
If that is correct, than the following regex might work for you. It may be, that you need to modify it a bit, to get JS to accept it:
<p\s+id='([a-zA-Z0-9_]+)'.*?id='end_of_\1'\s*\/>
This will give you any constellation with the criteria, describled above, and the name if the id as group 1, It should now be a simple task, to check if group1 contains the id you want to remove and then replace the whole match with an empty string.
If I understand your example correcty (I am not that good with JavaScript and my RegEx was based rather on the general perl-regex fashion) you could maybe do something like the following:
var patt=new RegExp("<p\s+id='"+id+"'.*?id='end_of_"+id+"'\s*\/>","g");
That way, you don't have to worry about group matching, although I find it to be more elegant, to match the id you wanted via a group instead of inserting it into the RegEx.

Categories