I'm trying to work out what regular expression I would need to change this string
html = '<img style="width: 311px; height: 376px;" alt="test" src="/img/1268749322.jpg" />';
to this
html = '<img width="311" height="376" alt="test" src="/img/1268749322.jpg" />';
with the help of Javascript.replace.
This is my start:
html = html.replace(/ style="width:\?([0-9])px*"/g, "width=\"$1\"");
Can anyone help me?
THANKS
It's generally considered a Bad Thing to do HTML parsing with RegExs.
Why not edit the DOM from JavaScript?
I'm not an expert on CSS, but isn't using style a better idea than width/height attributes?
You forgot the whitespace after : (\s*). You don't want ? there since it will miss >1 space or a tab
html = '<img style="width: 311px; height: 376px;" alt="test" src="/img/1268749322.jpg" />';
var d = document.createElement("div");
d.innerHTML = html;
var img = d.firstChild;
var width = parseInt(img.style.width, 10);
var height = parseInt(img.style.height, 10);
img.setAttribute("width", width);
img.setAttribute("height", height);
img.removeAttribute("style");
alert(d.innerHTML);
Of course, things get slightly easier if you don't start with a string ;-)
Gumbo is right, you should use DOM.
But to your regex: What is \? (question mark) supposed to mean? I would insert \s* (any number of whitespaces) at that position.
Yeah, normally I would do it with DOM, but in this special case I need to parse HTML-Code given from a WYSIWYG-Editor whish filters style-attributes. In general this is good, but for the pictures I would like to keep the set sizes with this html.replace-Hack.
This is the answer:
html = html.replace(/ style=".*?width:\s?(\d+).*?height:\s?(\d+).*?"/g, " width=\"$1\" height=\"$2\"");
Thanks for your help :-)
I can make it more elaborate if you wish, let me know how this works:
html = html.replace(/style=".*?width:\s?(\d+).*?height:\s?(\d+).*?"/g, "width=\"$1\" height=\"$2\"");
Edit: escaped qq
Related
I have to programmatically remove all iframes form a string that contais raw html base on the source of that iframe.
Eg: "... "
This is in a javascript string.
I thought about using String.replace based on some regex that excludes or some other approach.
Just need an example or some ideas, hope someone can help me because I am stuck with this and can't think about a propper solution.
Eg:
const regex = /Some weird regex to select the iframe piece/g
//Which I don't know how to write
// Happy to use something that removes all iFrames from the code as a quickfix regardless of the url
const raw_html = "\<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> ... \</html\>"
raw_html.replace(regex, '')
//This would remove whatever was on that regex with an empty piece of string.
If anyone has any ideas, they are welcome.
Thanks in advance
I've tried something like the example above, but couldn't write a working regex expression
Try this ↓↓↓
let html = '<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> <h2>Just another element to test the regex</h2> <p1>hello</p1> ... \</html\>';
let regex = /\n*\s*<iframe.*?\\?>.*?<\/iframe\\?>\s*\n*/gi;
html = html.replace(regex, '');
console.log(html);
If you will ever need to remove a different element, you can use this function:
function removeElementFromHtmlString(element, htmlStr) {
return htmlStr.replace(new RegExp(`\\s*<${element}.*>(?:.*<\\/${element}>)?`, 'g'), '');
}
let html = '<html\> ... \<iframe title="title" src="prohibited_url" width="100%" height="500" frameborder="0"\>\</iframe\> <h2>Just another element to test the regex</h2> <p1>hello</p1> ... \</html\>';
console.log(removeElementFromHtmlString('h2', html));
console.log(removeElementFromHtmlString('p1', html));
Hello I have a function that loops around and then eventually a string gets sent to a DIV tag class...
$(document).ready(function addcopy() {
/* global */
$(".Bands").append('<div style="display: inline-block;">[EDIT] <h7 style="color:#7A0029;line-height: 110%;text-transform: uppercase;">[Custom:Name]</h7> </div>');
});
It works fine... however the token [Custom:Name] may contain special characters such as single or double quotes etc...
I've looked around these forums and tried to adapt my code to various solutions offered and it never seems to work, could somebody help me?
Thanks for your help!
Alex
EDIT(1):
Getting somewhere, from Ockert's and LeFex's answer I've adapted it below but it still does not work (replace speech marks and special characters from token which html can't handle)...
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function (){
/* global */
var band = $("<div style='display: inline-block;'>[EDIT] <a href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.appendTo(htmlEncode('.Bands'))
});
You can change your script too
$(document).ready(function (){
var band = $("<div style='display: inline-block;'>[EDIT] <a class='link' href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.find('.name').html("some weird name !##$%^&*");
band.find('.link').attr("href","http://www.google.com");
band.appendTo('.Bands');
});
By splitting it up like that, enables you to set the name to anything you want. You can easily select the name element
Have a look at this jsfiddle http://jsfiddle.net/fL3gn056/2/
You could use document.createElement instead of just appending a string.
http://www.w3schools.com/jsref/met_document_createelement.asp
If you just create your div, a and h7-elements, use the appendChild function, and add style and attributes and content by setting element properties, you should end up with a sollution that allows any special characters.
Edit:
I could'nt get it working using that method; however, with the approach I suggested above, i got some working code:
var element = document.createElement("div");
element.style.display = "inline-block";
var link = document.createElement("a");
link.setAttribute('href', "[LINK]");
var text = document.createElement("h7");
text.style.color = "#7A0029";
text.style.lineHeight = "110%";
text.style.textTransform = "uppercase";
text.innerHTML = "[CUSTOM:NAME]";
//not sure what you're appending it all to, but do it here
document.getElementsByClassName("Bands")[0].appendChild(element);
element.appendChild(link);
link.appendChild(text);
With this snippet, all input special characters are interpreted as a string, not as code. Some calls I could have put in the same line, but this way you get an easy to read overview.
Here's an earlier thread on the subject, and the top answer brings the issue of performance of different approaches to discussion.
jQuery document.createElement equivalent?
I Just wanted to know, is there any way though which we can display only First Word from h2 Heading.
For Example:
In the source code it should look like this
<h2> Stackoverflow is an Ideal Place</h2>
However, on live website it should look like this
Stackoverflow
Basically, we want to display the FIRST WORD from the whole heading. However, Search engine should read the complete title.
Try this way
$(document).ready(function(){
var ac = $("#ac").text().split(' ');
$("#ac").text(ac[0])
})
You cannot do this with just CSS. You have pseudo-element selector for first letter, first line, but not first word.
You can set a width so that only the first word is visible (and use overflow:hidden of course), but that's not foolproof for all font families and sizes.
Finally you can do it with plain JavaScript or jQuery.
Plain JS:
var el = document.getElementById("ac");
el.innerHTML = el.innerHTML.split(/\s/)[0];
jQuery:
$("#ac").html(function(i, h) { return h.split(/\s/)[0];});
This will do what you want it to...
<h2 id="ac">Stackoverflow is an Ideal Place</h2>
$('#ac').html( function(i, h) {
var words = h.split(/\s/);
return ' <h2>' + words[0] + '</h2>';
});
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
I'm sure this will be really simple to someone out there but i'm wanting to use js to remove the last 10 characters in a string (that's inside a p element). Can anybody help please!!
Thanks in advance.
var ele = document.getElementById( 'myPId' );
ele.innerHTML = ele.innerHTML.substring( 0, ele.innerHTML.length - 10 );
Assuming your <p> element only contains text:
<p id="test">Here is lots of nice text</p>
... the safest way is to alter the text node directly:
var textNode = document.getElementById("test").firstChild;
textNode.data = textNode.data.slice(0, -10);