jquery find specific word on src and remove it - javascript

I need to find this word 500x462 in a src image att and remove it . Right now the image ends with 500x462 + jpg and i want it to end with image name + jpg
I forgot to say that the website is a wordpress theme generated by php so i need the script to run after the php
Heres a example of the code i want to change

Using a regex:
$("img").each(function(){
$(this).attr('src', $(this).attr("src").replace(/[\d]{3}x[\d]{3}/, ''));
});
This will remove any sequence of [3 digits][the letter x][3 digits] in all images src attribute.

Use the jquery and .replace(), so for example:
HTML:
<img src="http://www.placehold.it/500x462.jpg">
JQuery:
var string = $("img").attr("src");
var new_string = string.replace('500x462', '');
alert(new_string);
Working DEMO.

Assuming that the image src always ends with a file extension.
<img src="ABC500x462blah500x462.jpg">
<script>
var src = $('img').attr('src');
var textToCheck = '500x462';
$('img').attr('src', src.split('.')[0].replace(new RegExp(textToCheck +"$"),"") // check for the text occurring at the end
+ "." + src.split('.')[1]);
alert($('img').attr('src'));
</script>
Example : https://jsfiddle.net/mu2d6qr7/

I wrote a quick jQuery function to do this for you. First parameter is a jQuery selector and second parameter is the string you would like to remove.
window.srcRemoveString = function(selector, string) {
$(selector).each(function(){
var src = $(this).attr('src');
var filename = src.split('/');
filename = filename[filename.length - 1];
var newFilename = filename.replace(string, '');
$(this).attr('src', src.replace(filename, newFilename));
});
}
srcRemoveString('img', '500x462');

Best way to split text in image source
jQuery(".size-post-thumbnail").each(function(){
let src = jQuery(this).attr("src").split("-220x146");
src = src[0]+src[1];
jQuery(this).attr("src", src);
jQuery(this).removeAttr('srcset');
});

Related

Get and print hash in iframe

I Want to get hash from this url
http://www.mywebsite.com/#/aaaaaaaa
aaaaaaaa
And add to iframe :
<iframe src="http://www.example.com/url/aaaaaaaa" frameborder="0">
Javascript code :
<script>
var hhash = window.location.hash.substr(1);
alert(hhash);
</script>
You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substr() function to return the substring starting from that location:
var hhash =(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
document.write("<iframe src=\"example.com/url/\""+hhash+"frameborder=\"0\">");
Your title and question is a little bit misleading.
If you just want to print the hash tag, you can create an element and set the innerText to your hash, like so:
// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
document.querySelector( '.hash' ).innerText = lastPart;
<div class="hash"></div>
If you want to alter the src of the iFrame, you could use the first example combined with setAttribute.
// Use hash instead of href here! :) This is just to make the example work
const lastPart = window.location.href.split( '/' ).pop();
const src = 'http://example.org/url/' + lastPart;
document.querySelector( '.hash' ).setAttribute( 'src', src );
document.querySelector( '.url' ).innerText = 'iframe points to ' + src;
<iframe class="hash"></iframe>
<div class="url"></div>
You can get hash part (without #/) with:
var hash = window.location.hash.replace('#/', '');
Then you get the current iframe src attribute with :
var src = document.getElementsById('YourIframeId').getAttribute('src');
And now you update the iframe src:
document.getElementsById('YourIframeId').setAttribute('src',src + '/' + hash);

Add a part of URL in Iframe with javascript

i want to add last part of url in iframe
suppose my url is http://myweb.com/123456/
i want to add 123456 in iframe like
<iframe src ="http://myweb.com/demo.html?user=123456"></iframe>
Please Help, Thanks in advance
Here the solution. Purely using JavaScript no jQuery.
Steps:
Extract url's last part.
Get the iframe element using it's id
Get the current value of src attribute of iframe
Append the concatenate the extracted last part of url to current value of src
Update the attribute value
var url = "http://example.com/12345";
var lastPart = url.split('/').pop();
console.log("Last part of url: " + lastPart);
var myIframe = document.getElementById('myIframe');
var iframeSrc = myIframe.getAttribute("src");
console.log("Initial src value: " + myIframe.getAttribute("src"));
myIframe.setAttribute("src", iframeSrc + lastPart);
console.log("src after appending: " + myIframe.getAttribute("src"));
<iframe id="myIframe" src ="https://example.com?user="></iframe>
You can just the following to add any values you may need to the end of the src (Note this is jQuery, so this may not be what you are interested in):
var value = "123456";
$('iframe').attr('src', $('iframe').attr('src') + value);
document.write("New URL: " + $('iframe').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe src ="http://myweb.com/demo.html?user="></iframe>

Find a element and append a image

I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work
If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);
Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO
if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

Replace Image src before append html code

I have a html content variable in js as
var htmlIs = '<p><img src="images/stories/fight_bpl.jpg" /></p>';
and I am appending it to the div using
$("#divId").append(htmlIs);
but here I just want to replace the src want to add the external image link here before append the content so how can I do this?
You can create a jQuery object:
$(htmlIs).find('img').attr('src', 'url').end().appendTo('#divId');
http://jsfiddle.net/BdnYd/
For multiple images:
var htmlIs = '<p><img src="images/stories/img_1.jpg" /><img src="images/stories/img_2.jpg" /></p>';
var urls = ['url1', 'url2']
$(htmlIs).find('img').each(function(i){
$(this).attr('src', urls[i])
}).end().appendTo('#divId');
http://jsfiddle.net/TUFcX/

Categories

Resources