append div in jquery with quotes in field - javascript

hello i have a this code but i have a problem with quotes in javascript:
var content = 'peter says: 'hello'';
and
var append = '<div class="'+content+'>';
how proteted quotoes ?? attribtties class only show: peter says:
thanks and sorry for my english.

var content = "peter says: 'hello'";
Escape the quotes.
This would work as well (put a back slash in front of the quote you want to display):
var content = 'peter says: \'hello\'';

You can do this by escaping it using \"
var content = 'peter says: \"hello\"';
However this should work
var content = 'peter says: "hello"';
To support, I have added JSFiddle
There is no need to escape double quotes within single quotes or vice versa. However escaping is a standard approach.
Here I got a reference too

Is that fiddle answers your question
<div id="test">
</div>
$(function()
{
var content = "petersays: 'hello'";
var classToAppend = "class=\""+content+"\"";
var append = "<div +classToAppend+">test</div>";
$("#test").append(append);
});
http://jsfiddle.net/29fLy/2/

Related

Why my regex is not working in react but working anywhere else (e.g. regex tester online)? [duplicate]

I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?
<script type="text/javascript">
var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);
</script>
Thanks a lot!
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
This is an old question, but I stumbled across it and thought I'd share the method I used:
var body = '<div id="anid">some text</div> and some more text';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
sanitized will now contain: "some text and some more text"
Simple, no jQuery needed, and it shouldn't let you down even in more complex cases.
Warning
This can't safely deal with user content, because it's vulnerable to script injections. For example, running this:
var body = '<img src=fake onerror=alert("dangerous")> Hello';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;
Leads to an alert being emitted.
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
This is a solution for HTML tag and &nbsp etc and you can remove and add conditions
to get the text without HTML and you can replace it by any.
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, 'ReplaceIfYouWantOtherWiseKeepItEmpty');
}
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.
#license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
var res = tmp.textContent || tmp.innerText || '';
res.replace('\u200B', ''); // zero width space
res = res.trim();
return res;
}
you can use a powerful library for management String which is undrescore.string.js
_('a link').stripTags()
=> 'a link'
_('a link<script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
my simple JavaScript library called FuncJS has a function called "strip_tags()" which does the task for you — without requiring you to enter any regular expressions.
For example, say that you want to remove tags from a sentence - with this function, you can do it simply like this:
strip_tags("This string <em>contains</em> <strong>a lot</strong> of tags!");
This will produce "This string contains a lot of tags!".
For a better understanding, please do read the documentation at
GitHub FuncJS.
Additionally, if you'd like, please provide some feedback through the form. It would be very helpful to me!
For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
The selected answer doesn't always ensure that HTML is stripped, as it's still possible to construct an invalid HTML string through it by crafting a string like the following.
"<<h1>h1>foo<<//</h1>h1/>"
This input will ensure that the stripping assembles a set of tags for you and will result in:
"<h1>foo</h1>"
additionally jquery's text function will strip text not surrounded by tags.
Here's a function that uses jQuery but should be more robust against both of these cases:
var stripHTML = function(s) {
var lastString;
do {
s = $('<div>').html(lastString = s).text();
} while(lastString !== s)
return s;
};
The way I do it is practically a one-liner.
The function creates a Range object and then creates a DocumentFragment in the Range with the string as the child content.
Then it grabs the text of the fragment, removes any "invisible"/zero-width characters, and trims it of any leading/trailing white space.
I realize this question is old, I just thought my solution was unique and wanted to share. :)
function getTextFromString(htmlString) {
return document
.createRange()
// Creates a fragment and turns the supplied string into HTML nodes
.createContextualFragment(htmlString)
// Gets the text from the fragment
.textContent
// Removes the Zero-Width Space, Zero-Width Joiner, Zero-Width No-Break Space, Left-To-Right Mark, and Right-To-Left Mark characters
.replace(/[\u200B-\u200D\uFEFF\u200E\u200F]/g, '')
// Trims off any extra space on either end of the string
.trim();
}
var cleanString = getTextFromString('<p>Hello world! I <em>love</em> <strong>JavaScript</strong>!!!</p>');
alert(cleanString);
If you want to do this with a library and are not using JQuery, the best JS library specifically for this purpose is striptags.
It is heavier than a regex (17.9kb), but if you need greater security than a regex can provide/don't care about the extra 17.6kb, then it's the best solution.
Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.

Replacing text with smiley image using Jquery

Please Guys, I am new to Jquery. I have been searching for a suitable help since last week but I can't find any. I want to replace a text with a smiley image using jquery but I have no idea how to run this. For example, I want this text "I am feeling :happy;" to be replaced with "I am feeling <img src='happy_face.gif' />" and "He is :sick;" to be replaced with "He is <img src='sick.gif' />".
Here is what I have gotten so far but it still displays the text instead of the image:
:) :(
<script src="js/jscript.js"></script>
<script>
var emotes = [
[':happy;', 'happy.gif'],
[':sick;', 'sick.gif']
];
function applyEmotesFormat(body){
for(var i = 0; i < emotes.length; i++){
body = body.replace(new RegExp(emotes[i][0], 'gi'), '<img src="emotes/' + emotes[i][1] + '">');
}
return body;
}
Thanks in advance
It is actually quite simple.
You only need one line to find and replace string instances in the HTML:
$("body").html($("body").html().replace(/:happy;/g,'<div class="happy-face"></div>'));
This sets $("body").html() to the $("body").html() with :happy; replaced with <div class="happy-face"></div>.
/:happy;/g is RegEx to find the string :happy; globally (g)
https://jsfiddle.net/heowqt1u/2/
You can use following code:
var a = [[':happy;','<img src="happy_face.gif" />'],[':sick;',"<img src='sick.gif' />"]];
a.forEach(function(item) {
$('p').each(function() {
var text = $(this).html();
$(this).html(text.replace(item[0], item[1]));
});
});
Working example here: Smiley codes replace

Javascript: How to include a url in a string variable?

new to this javascript thing. This is driving me crazy!
How do I add a URL in a string variable?
This is what I have:
function getRiskMessage(){
var msg = " visit our advice website at <a href=\'http://www.example.com\'>this site</a>";
if(totalRiskScore > 25){
//this message (High Risk)
msg2 = show();
}//close if
return msg;
}
but when i output it to a div instead of a link 'this link' - I get the a tag and url as string like above.
What am I doing wrong, need to understand this.
tl;dr You're using createTextNode, which creates a plain-text node. Don't do that :) Use the innerHTML property instead. See below for more details.
You don't need to escape quotes unless they resemble the start and end quotes:
var foo = "Visit <a href='http://bing.com'>Bing</a>.";
In the above, the string begins and ends with double-quotes, so single-quotes can be used without any problems.
var foo = "Visit Bing.";
In the above, we use double-quotes around the string, and around the [href] attribute. As a result, the inner-quotes (around the attribute) must be escaped so they don't confuse the parser.
Lastly, when you output, make sure to output as HTML:
div.textContent = foo; // Represents foo as plain text
div.innerHTML = foo; // Interprets foo as HTML
div.appendChild( document.createTextNode( foo ) ); // Similar to textContent
div.appendChild( document.createElement( "span" ) ).innerHTML = foo; // HTML
Example:
document.querySelector( ".msg" ).innerHTML = "Visit <a href='http://bing.com'>Bing</a>.";
<div class="msg"></div>
This is a basic example on how to insert html using plain javascript:
document.getElementById('your-div').innerHTML = msg
Here is a fiddle of your case: demo
Thy this:
var msg = document.createElement('span');
msg.innerHTML = " visit our advice website at <a href=\'http://www.example.com\'>this site</a>"
container.appendChild(msg);
Working demo: FIDDLE

RegEX to replace <div /foo> with </div>

I'm a newbie in using RegEX and I could really use some help.
I'm doing some string replacements and I currently get the output
<div /foo>
Instead of
</div>
str = "[foo][/foo]";
Regex used:
str= str.replace(/\[/g, '<div ').replace(/\]/g, '>');
Output wanted:
<div foo></div>
Can someone help me to replace the string in the right way?
Thank you very much!
Not much content to your question so I just posted something which gets the job done. Note this assumes you do not care about anything after the opening tag, it only keeps the name of the tag and replaces it by </tagname>.
var str = "<div /foo>";
var replaced = str.replace(/<(\w+).*/, '</$1>')
// "</div>"
This one could suit your needs:
\[([^\]]+)\](.*?)\[/\1\]
Replace with: <div $1>$2</div>
Visualization by Debuggex
Demo on RegExr
PS: don't forget to escape the / if using JavaScript's regex literal, i.e.:
/\[([^\]]+)\](.*?)\[\/\1\]/g
How about:
str= str.replace(/\[(.+?)\]\[\/\1\]/g, '<div $1></div>');
You can do like this also.
var str = "[foo][/foo]";
//replace <, > with [, ]
var signReplace = str.replace(/\[/g, '<').replace(/\]/g, '>');
tagReplace = signReplace.replace(/foo/g, 'div'); //replace div with foo

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

Categories