I have a jQuery variable merImg like this
var merImg = '<img src="http://om.com/pion/thumbnail/11x65/aa/img.jpg" border="0" align="left" height="11" width="65">';
I want to replace thumbnail/11x65 in the src with image/40x using jQuery. Is there a regex to do this easier? Or any logic at all to change it?
Also I want to remove the height and width attribute to the img tag. How do i go about it?
You could use the standard replace() method of javascript:
merImg = merImg.replace('thumbnail/11x65', 'image/40x');
as the first argument you can also pass a regExp like this
merImg = merImg.replace(/your regexp/, 'image/40x');
To remove height and width in this case you could replace them with an empty string:
merImg = merImg.replace('width="65"', '');
merImg = merImg.replace('height="11"', '');
I'm no experto of regular experssions but you can write a general regular expression to strip away width and height attributes from a string.
Also a llot of people suggest (correctly) that you should use an HTML parser to parse HTMl. Try to google it if you need more info about it
But in this particulare what i've written should work
Related
I have HTML tag with link in background style and I want this link to be a string in my JS file. How can I do that?
<div class="bmlistt" style="background: url('b.ppy.sh/thumb/845746.jpg';)"></div>
You can grab the it using this:
var bg = $("div.bmlistt").css('background');
bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
How about the following:
const imageElement = document.getElementsByClassName('bmlistt')[0];
let image = imageElement.style.background.replace('url("', '').replace('")', '');
console.log(image);
<div class="bmlistt" style="background: url(b.ppy.sh/thumb/845746.jpg)"></div> <!-- Fix ";" in style attribute -->
No need for big libraries. querySelector to get the div. I would use its style.background or style.backgroundImage property. The latter of those only contains the image itself, and not any other background css you might specify in a real life scenario, possibly making it easier to extract the url.
Unfortunately with your specific HTML that doesn't work, because of an error in the CSS (the semicolon). So in that case you have to parse the style attribute as text, rather than relying on the style object property, which contains the browser's interpretation of your CSS. Both solutions are shown below.
var theDiv = document.querySelector('.bmlistt');
console.log(theDiv.style);
// Doesn't work because of error in the CSS. Otherwize this would do it.
var css = theDiv.style.backgroundImage;
console.log(css.substr(5, css.length - 7));
var attr = theDiv.getAttribute('style');
// This, if you know the length of the 'overhead' around the url, or
// a regular expression.
console.log(attr.substr(17, attr.length - 20));
<div class="bmlistt" style="background: url('b.ppy.sh/thumb/845746.jpg')"></div>
I have raw html with link tags and the goal I want to achieve is extract href attribute from tags and all text between tags except tags.
For example:
<br>#EXTINF:-1 tvg-name="1377",Страшное HD<br>
<a title="Ссылка" rel="nofollow" href="http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C01_STRASHNOEHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2" target="_blank">http://46.61.226.18/hl…variant.m3u8?version=2</a>
<br>#EXTINF:-1 tvg-name="983" ,Первый канал HD<br>
<a title="Ссылка" rel="nofollow" href="http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C06_1TVHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2" target="_blank">http://46.61.226.18/hl…variant.m3u8?version=2</a>
have to convert to:
#EXTINF:-1 tvg-name="1377",Страшное HD
http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C01_STRASHNOEHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2
#EXTINF:-1 tvg-name="983" ,Первый канал HD
http://4pda.ru/pages/go/?u=http%3A%2F%2F46.61.226.18%2Fhls%2FCH_C06_1TVHD%2Fbw3000000%2Fvariant.m3u8%3Fversion%3D2
I tried different regex's:
Here what I did
var source_text = $("#source").val();
var delete_start_of_link_tag = source_text.replace(/<a(.+?)href="/gi, "");
delete beginning of the tag to the href attribute
var delete_tags = delete_start_of_link_tag.replace(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gi, "");
delete all tags </a>, <br>
example
And then I want to delete all text after href values to the end of the line.
What regex should i use in replace method or maybe where is a some different way to do this converting?
Formatting Anchor Tags
In your example , you are not replacing the "> part form the html.
So check this example
use this code to remove everything after href close quote(' or ")
var delete_tags = delete_start_of_link_tag.replace(/".*/gi, "");
And few things to notice are
1.The value in href is enclosed in single quote(') or double quotes("), both are valid.
2.The exact regex to match all href in a given string or content is href=[\"|'].*?[\"|']
3.Some patterns in href values , I came across are below.
http://www.so.com
https://www.so.com
www.so.com
//so.com
/socom.html
javascript*
mailto*
tel*
So if you want to format URL's then you have consider the above cases and i may have missed some.
Looks like you're already using jQuery.
Get the href of each anchor
$('a').each(function(){
var href = $(this).attr('href');
});
Get the text of each anchor:
$('a').each(function(){
var text = $(this).text();
});
You haven't shown a wrapper element around these but you can get the text (without tags) of any selection.
var text = $('#some_id').text();
Example
I've been trying for hours and I've looked a lot of samples on StackOverflow, but I can't fix my simple script.
I grabbed DOM with jQuery
var color = $('#bscontainer').html();
and now the content of color is:
<img src="resources/P/Blue_BG_2Col.png" id="bg">
<img src="resources/P/Blue_Content_2Col.png" id="content">
<img src="resources/P/Blue_Title_ExchangeRate.png" id="title">
<img src="resources/P/Blue_SubTitle_2Col.png" id="subtitle">
<img src="resources/P/Blue_Disclaimer_Disclaimer.png" id="disclaimer">
My idea is to change all the Blue to Green, and I already try this:
curColor="Blue";
newColor="Green";
t=color.replace(curColor,newColor);
It simply doesn't works. Any ideas?
To answer your question directly, replace in javascript when it takes a string parameter as the needle, only replaces the first instance. To replace all instances within a string, use a global regular expression:
str.replace(/Blue/g, 'Green');
You really ought to just modify the src attributes of the img tags though. That is the more proper way to attack this. Changing the html like you are trying to will lose any events or data bound to the DOM elements.
So basically you want to find each image in your color element and replace Blue with Green in the src attribute -- This is one way you can do it:
var color = $('#bscontainer');
color.find('img').each(function(){
curColor="Blue";
newColor="Green";
this.src = this.src.replace(curColor,newColor);
});
No need for the .html() part of your code...
Use a callback function to actually update the HTML, and use a regular expression (object) to replace all instances at once:
$('#bscontainer').html(function (i, str) {
curColor = new RegExp("Blue","g"); // global replace
newColor = "Green";
return str.replace(curColor, newColor);
});
I'm trying to find a particular character in a div and wrap it in a span tag.
I thought I could use something like:
$('.breadcrumb:contains("»")').replaceWith('<span>»</span>');
But this changes the whole breadcrumb div.
What am I doing wrong?
.replaceWith only works on nodes. You need the string method .replace() instead:
var $bc = $('.breadcrumb');
$bc.html($bc.text().replace('»', '<span>»</span>'));
Like Mr. Craver suggested, you can also call:
$bc.html(function(i, html) {
return html.replace('»', '<span>»</span>');
});
Example: http://www.jsfiddle.net/jwJKr/
var $bc = $('.breadcrumb');
$bc.html($bc.text().split('»').join('<span>»</span>'));
Works better to replace all characters.
I have a function that reads the content of an element, replaces a word with a link and then rewrites the content back into the element. Obviously this means that all events that were previously set are lost.
Does anyone know of a function/method that could find and replace the content of an element without losing the events?
Edit: Without using a library
Here is my current code that does not destroy the events but turns <, for example, into <, so I can not append HTML. This is the closest I have got:
element.appendChild(document.createTextNode(content));
My original code worked but got rid of the events:
element.innerHTML += content;
By using jQuery you could do it with the text() method
var str = $('#element-id').text();
str = yourReplaceFunction(str);
$('#element-id').text(str);
Edit:
Another option would the innerHTML property. It's not very elegant but works nevertheless.
var strElem = document.getElementById('element-id');
var str = strElem.innerHTML;
str = yourReplaceFunction(str);
strElem.innerHTML = str;
Edit2:
Yet another option would be to wrap the text you want to replace inside of a separate tag, for example <span>.
<div id="container">
<a id="link-with-events">Link</a>
<span id="replaceable">The Text Gets Replaced</span>
<a id="more-links-with-events">Another Link</a>
</div>
Then you'd simply access and replace the contents of the span tag, leaving the surrounding elements untouched.
Assuming the tag contains just text (and not additional tags):
element.firstChild.nodeValue=content;
See https://jsfiddle.net/Abeeee/ubj6hte4/