I have an html string and I want to replace any instance of an html attribute being set with single quotes with double quotes.
So for example, I want to replace
<script src='foo.js'></script>
with
<script src="foo.js"></script>
However, I want to do this without affecting any single quotes that might be in javascript statements or in text within the html.
Eg
<script> var foo = '67'; </script>
should be unaffected and
<div id='foo'> 'hi' </div>
should become
<div id="foo"> 'hi' </div>
Is there any easy way to do this?
For a given element selecting it with jquery and then reading its outerHTML does this but I want to do it to an entire page of html all at once.
Thanks!
Try this:
var str = "<br style = 'width:100px'/> test link";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
You can refector it to strictly match your case.
Answering my own question as I think the easiest solution to this is what is shown in this fiddle and does not require jquery or regexps:
http://jsfiddle.net/QdUR5/1/
<html id="foo"></html>
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
Basically you just need to set the inner html of an html element to the html string without the html tags and then output the html elements outer html.
I think that is a bit simpler than using a regexp although that is an awesome regexp Mike :)
Related
So I'm trying to do something very simple and I'm stuck. I have a String variable and within that variable I Wanna set line break so certain part of the text goes to new line.
What I have tried:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
I have tried many variations but its just not working. Am I being stupid and missing something very obvious?
Not a duplicate as I have tried the <br/> and it has not worked.
Update:
The variable is being printed in the browser HTML like so {{title}}
Here are two demonstrably working versions...
White Space
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
Angular Version:
<h1 style="white-space: pre;">{{title}}</h1>
HTML Break
Solution two... you want to use HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
Use ng-bind-html if you want to allow HTML during binding.
In html add style:
<div style="white-space: pre-line">{{DialogText}} </div>
Use '\n' to add newline in the typescript.
this.DialogText = "Hello" + '\n' + "World";
Same in stackblitz: https://stackblitz.com/edit/angular-rpoxr5linebreak
You can also use a readonly textarea element instead of <div or <p> to keep the format of original string.
try like this
<div ng-bind-html="myMsg"></div>
$scope.myMsg = `Below is the result: <br>Successful:1, <br>Failed:2` // Use backtick
You have done the right thing.
But if you are showing this in a browser, the \n means didley.
You have to do:
title: string = "My<br>Title"
Now if you are using a fancy front end tool like React, you will have to deal with unsafe HTML in strings...
I'm trying to render some HTML on the fly in my website without success. I've tried using jQuery's .html() function as below:
My html
<div id='open_ender_output'></div>
My JQuery
var openEnderContent = "<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
//openEnderContent comes from my backend
$('#open_ender_output').html(openEnderContent)
The result is
<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>
Is there a way to make the browser render that result on the fly so it reflects the specific styles set on the text?
Decode the content by creating a temporary element.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').html(
// create an element where the html content as the string
$('<div/>', {
html: openEnderContent
// get text content from element for decoded text
}).text()
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
Or you need to use a string which contains unescaped symbols.
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='open_ender_output'></div>
You're on the right track. You need to differentiate between single and double quotes when creating a string. You're closing your string by adding double quotes inside double quotes.
Use the var below.
var openEnderContent = "<span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>";
$('#open_ender_output').html(openEnderContent);
Fiddle for example: https://jsfiddle.net/acr2xg6u/
Change your jQuery to
var openEnderContent = '<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>';
$('#open_ender_output').append(openEnderContent);
Parsing problem from what I can tell.
"<p><span style="color: #ff0000;">DDD</span>!!!!!<strong>666666666666</strong></p>"
You cannot create strings like that. If you are inside one, you must use the other:
"My name is 'Josh Crowe'"
'My name is "Josh Crowe"'
Here's corrected code:
"<p><span style='color: #ff0000;'>DDD</span>!!!!!<strong>666666666666</strong></p>"
Now i create a jQuery object by using
var content = $("Some string" + <a target="_blank" href="http://www.mypage.com"> + </a>);
But this seems not working.
How to fixed it?
The jQuery constructor will only create you an element. It won't display it on the document until you append it. Also, the elements must be parsed as a string. Example:
var content = $('<span>Some string</span><a target="_blank" href="http://www.mypage.com">Link</a>');
content.appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In your code, the HTML wasn't a string, so it most likely showed a SyntaxError or a TypeError.
Try substituting a string representation of content for wrapping in jQuery()
var content = "Some string" + "<a target=_blank href=http://www.mypage.com> + </a>";
$("body").append(content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I am trying to replace a text in javascript using a regular expression like following [example of what I am trying to do]:
<html><head></head>
<body>
<div id="div1">This is Old</div>
<script>
var message = "Hi";
var str = document.getElementById("div1").innerHTML;
var newstr = str.replace(/Old/g, "<div onclick='say(\""+message+"\");'>New</div>");
document.getElementById("div1").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>
This is a sample code of what I am trying to do in a large application. Our script is injected in thrid party html pages, so we dont have control over the html.
If you run this code, you will see that the text appears to be broken and if you just remove the "Old" from the title tag it will work fine. I cannot change the html, so I have to modify the script to handle this.
Is there a way I can put some regular express that can bypass the replacement of the text in case if it occurs in between "<" and ">"?
or some other way to solve this.
I cannot use DOM to do the replacement, as it crashed the page when there were too much text, I am doing full page text replacement.
Thanks in advance for your help :)
EDIT: Changed the code to make it working :)
I might be unrelated but, you may need to replace message variable inside the replaced text. Since you declared message variable locally, it will not be available outside.
EDIT:
For your question, you can do that with RegEx but it will be quite hard. If I got time I might work on it a bit.
EDIT 2:
Try this one, it makes sure the Old is not in a tag.
>[^><]*(Old)[^<>]*<
EDIT 3:
This works file too, starting > is not necassary
[^><]*(Old)[^<>]*<
EDIT 4:
<html><head></head>
<body>
<div id="div1">This is Old</div>
<script>
var message = "Hi";
var str = document.getElementById("div1").innerHTML;
var newstr = str.replace(/([^><]*)Old([^<>]*<)/g, "$1<div onclick='say(\""+message+"\");'>New</div>$2");
document.getElementById("div1").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>
Make your replace:
str.replace(/(>[^<]*)Old/g, "$1<div onclick='say(\"message\");'>New</div>");
Which basically means "Old not in an HTML tag"
Wouldn't it be simpler to assign id to <a> element instead and then run the same replace() on it's innerHTML (which shouldn't contain the tag's title attribute):
<html><head></head>
<body>
<div id="div1"><a id="link" href="#" title="This is Old">This is Old</a></div>
<script>
var message = "Hi";
var str = document.getElementById("link").innerHTML;
var newstr = str.replace(/Old/g, "<div onclick='say(\"message\");'>New</div>");
document.getElementById("link").innerHTML = newstr;
function say(message)
{
alert(message);
}
</script>
</body>
</html>
Why doesn't this work? innerHTML cannot take in something so complicated?
<html>
<head>
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td><label for="name">Name:</label></td><td><input type="text" id="name"></input></td></tr>"; +
"<tr><td><label for="remarks">Remarks:</label></td><td><input type="text" id="remarks"></input></td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>
Something less complicated like this works:
var html = "<table><tr><td>123</td><td>456</td></tr></table>";
You need to either escape double quotes within the string you're assigning to the html variable, or just enclose the string with single quotes. Use a text editor with syntax highlighting and errors like that will jump out at you right away. You also have an extra semicolon in your assignment.
Your quoting is broken. You are using double quotes inside the string:
"<tr><td><label for="remarks">Remarks:</label></td><td><input ....
the Firefox error console should always be your first stop, errors like that are always logged there.
Your string is delimited using double quotes and also uses them within the string. Switch to using single quotes within the string.
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>"; +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";
instead of double quotes use single quotes as shown below:
var html = "<table><tr><td><label for='name'>Name:</label></td><td><input type='text' id='name'></input></td></tr>' +
"<tr><td><label for='remarks'>Remarks:</label></td><td><input type='text' id='remarks'></input></td></tr></table>";
Enjoy coding!!
You need to either escape double quotes or use single quotes within the string destined for that innerHTML.
There is an error in your string , try this :
var html = "Name:"; +
"Remarks:";
document.getElementById("addtable").innerHTML = html;