Convert Html to plain text - javascript

I used tinymce editor for rich text editor. My problem is when i save the text, its saves in html format like
<p> Hello world<p/>
I need a plain text i.e. "Hello World" in above example.
I search on google and I find something like html encode. I don't know what that is. I am new to this concept. I am using asp.net MVC 5 and I have used tinymce as:
Model is
namespace ProjectNSAS.Models{
public class AboutModels
{
[Key]
public int Id { get; set; }
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Content { get; set; }
}

It's probably not the best of help,, but a .txt file is also a form of plain text. If you just want to see the code and not run it, try doing something with .txt.

HTML has some characters which mean special things to HTML. Specifically, opening and closing tags ("<" and ">"), when put together, mean that the content between them specifies an element. If you have these characters when they aren't meant for HTML tags, HTML parsers have trouble. When an HTML file wants to represent literal greater-than or less-than characters, it "encodes" them by replacing them with ">" and "<", respectively. Browsers and other HTML-consuming products know that those two strings represent "escaped" HTML characters.
.NET has a small library for escaping/unescaping HTML strings - it's the HttpUtility class. specifically, check out HttpUtility.HtmlEncode and HttpUtility.HtmlDecode

Under the hood the editor provides a getcontent method, the integration doesn't provide an access point that I can easily find. However the implementation is rather simple.
TinyMCE has the following code to convert it's html to text:
In: jquery.tinymce.js:
... t.getContent().replace(/<(?:"[^"]*"|'[^']*'|[^'">])*>/g, "") ...
Which basically is just a javascript regex replacement, do the same in your C# code, and then decode the html.
Here is a sample controller:
public class TinyController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(TinyMCEModelJQuery model)
{
var foo = model.Content;
Regex regex = new Regex("<(?:\"[^\"]*\"|'[^']*'|[^'\">])*>");
var htmlPlainText = regex.Replace(foo, string.Empty);
var plainText = HttpUtility.HtmlDecode(htmlPlainText);
// do what you need with plainText
return View();
}

Related

Passing params through URL - Single quotes become '

I'm working with a ASP.NET project. We are passing params through the url and every time a single quote is passed the url changes all single quotes to %27 and the actual value read in through the javascript changes all single quotes to '
Can someone tell me how I can maintain the single quotes as our parameters need to match the exact values. This is my code.
public class Model
{
public string example {get; set;}
}
public ActionResult Index(string example)
{
var model = new Model();
model.example = example;
return View(model);
}
Index.cshtml at the bottom ---------------------
<script type="text/javascript">
var example = "#Model.example";
Main();
</script>
Javascript -----------------
console.log(example);
Examples: www.example.com?example=Turtle's_Are_Cool
Changes the url instantly to => www.example.com?example=Turtle\%27s_Are_Cool and the JavaScript outputs Turtle&#39s_Are_Cool
If you want to do it on the server side you can use
Server.URLEncode("Turtle's_Are_Cool"))
If you want to manage the same on client-side you can replace ' with '
example = example.replace(/'/g, "\'");
But if you have got a single quote coming from server-side and you want to convert it at client-side then the easiest way is to use HTML element as shown in the below question
Unescape apostrophe (') in JavaScript?

How to use Razor display template to convert string to html string

I'm new to razor and display templates so please correct me where I'm wrong. I'm working with a string that contains HTML. If I try converting it directly to a HtmlString, my Ajax form refuses to submit. As a workaround I tried to use Display templates with the goal of achieving something like this
My #foreach loop contains this
#Html.DisplayFor(modelItem => myModel.myString, "HtmlString")
My DisplayTemplate contains this
HtmlString.cshtml
#model String
#{
new HtmlString(#Model);
}
So if myString = "<ul><li>my text</li></ul>"
I would like my ajax form to display my text
What I have now doesn't work and returns nothing. Please help with what I'm doing wrong.
You should use #Html.Raw() like;
#Html.Raw(Model.myString)
Hope this helps.
I have made some minor modifications to your code. Please test and implement.
In your HtmlString.cshtml file, replace your code with the following. This is a partial view that is being called in a foreach loop and is passed a string value that contains HTML. #Html.Raw is used to displayed the HTML as HTML:
#model String
#Html.Raw(Model)
Your view will receive a list of strings that is passed from your controller's action method. Each string contains the HTML:
#model List<string>
#foreach (var s in Model)
{
#Html.Partial("HtmlString", s)
}
This is the data that I used to test your scenario. The HTML that is outputted is correct:
public ActionResult TestMethod1()
{
List<string> strings = new List<string>();
strings.Add("<ul><li>my text</li></ul>");
strings.Add("<ul><li>my text</li></ul>");
return View(strings);
}
The resulting output looks like this:
<ul><li>my text</li></ul><ul><li>my text</li></ul>
I hope that I understood your question correctly?

how to solve C# Json Serialization parsing in javascript with quoutes?

I am serializing a C# Class AnnouncementClass
public class AnnouncementClass
{
public string application;
public List< AnnoucementsMessages > annoucements = new List<AnnoucementsMessages>();
}
public class AnnoucementsMessages
{
public string message;
public string startdate;
public string priority;
}
using the serializing method
string jsonboj = new JavaScriptSerializer().Serialize(announcementClass);
after that I write the json in the javascript by using the <%# > Tag and perform a page.databind() in the page and later in javascript y I use Json.Parse(jsonObj) to generate the json file
but that's giving me a problem
if in the message part i insert a double quoute it breakes the json.parse, even if i try to scape it.
Is there a proper way to translate the json to the javascript side?
do i need to replace something before the c# serialization ?
Thank you
Solution found, thank you
when parsing , Javascript will reduce all the scapes so, using \" = " and \\="
so i had to replace the \" with ;quot

Print managed bean property as JavaScript variable

I'm trying to print java string return values into script java .
this is my method in java class
public static String getchamps (){ //Bdconnection class
String str;
{
str = "date" ;
}
return str ;
}
the question is how can i have this code
<script type="text/javascript" >
"date"
</script>
You should in this context look at JSF as a HTML code generator. You can use JSF tags/components and EL expressions to let it produce the desired HTML output. As JavaScript is as being a client side language technically part of HTML (not of JSF!), you can just do the same for JavaScript.
Once you fix that bad static method to really comply the Javabeans specification as below:
public String getChamps() {
return "date";
}
Then you can just let JSF print it as if it's a JS variable as below:
<script>
var champs = "#{bean.champs}";
</script>
To verify the result, just open the JSF page in webbrowser and do rightclick, View Source. You should see something similar to:
<script>
var champs = "date";
</script>
Beware of JS-special characters in the string though! This would fail if the string contains e.g. a doublequote or even a newline. If that's the case, then you'd better escape it using an EL function as shown in this answer: Escape JavaScript in Expression Language.
Do this:
<h:inputText id="propertyId" value="#{Bdconnection.str}" />
and access in script
document.getElementById('propertyId').val();

innerHTML doesn't respect indentation

I have a code on the client side that receives some data through socket.io with a node.js backend. I receive some indented data (which is some code in string format). I can alert the code out and I see it is indented in the alert, but when I do document.getElementById('myDiv').innerHTML = receivedData.indentedData the data outputted in myDiv is not indented, but just in a single line.
Do you know a way to have the indentation respected in some string when filling an HTML element?
To be more precise I alert the data in this form:
class Motto {
public static void main(String[] args) {
System.out.println("Java rules!");
}
}
But what I see in myDiv is this:
class Motto { public static void main(String[] args) { System.out.println("Java rules!"); } }
Thanks
Most of the time, outputting code like this, you'll want to wrap it in <pre> and <code> tags.
document.getElementById('myDiv').innerHTML = "<pre><code>"+receivedData.indentedData+"</code></pre>";
That's what the StackOverflow markdown editor does for code snippets.
innerHTML respects indentation. The problem is the way how HTML itself represents data: it displays all whitespace as a single space. Replacing \n with <br> is only a partial solution because tabs won't still be saved. Better use #myDiv { white-space: pre; } in your CSS.
Replace \n with <br>. As you may know, line breaks aren't displayed as such in HTML, but are treated as spaces.
Try this:
document.getElementById('myDiv').innerHTML =
receivedData.indentedData.replace(/\n/g, '<br>');
In HTML, line breaks are ignored, you have to use <br> for line breaks.

Categories