Decoding the chinese characters in input text field - javascript

I want to decode the chinese characters into the input text field.But it is showing the field as it is.
But it is showing the "&#28450 ;&#23383 ;" instead of chinese characters
Expected output :漢字
output :&#28450 ;&#23383 ;
it is working fine when i use textarea
input type="text" id="chinese"
function myFunction() {
var uri_dec = decodeURIComponent("漢字")
document.getElementById("chinese").value= uri_dec;
}
Please help me on this
Thanks in advance

decodeURIComponent doesn't do what you think it does. It will decode "%E6%BC%A2%E5%AD%97" (an URI-encoded string) into "漢字"; but you have HTML entities, not an URI-encoded string.
var ent_enc = "漢字"
var div = document.createElement('div');
div.innerHTML = ent_enc;
var ent_dec = div.textContent;
document.getElementById("chinese").value = ent_dec;
<input type="text" id="chinese">

Related

txt.replace </blockquote> in textarea js

I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.

Preserve line breaks while substituting anything except the first letter and punctuation marks

jQuery("#memorize-form").submit(function(){
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
jQuery("#result").html(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="memorize-form" action="" method="get">
<textarea id="n-text" rows="10"></textarea>
<button id="memorize-submit">Convert</button>
</form>
<span>Result: </span><span id="result"></span>
This code replaces all the letters except the first on with the underscore. The punctuation should be made intact.
The text is input by the user.
The problem with it is that the text contains a line break, the line break is not preserved. It should be preserved.
Try this:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.
P.S.: The result disappears from the screen. Why is this?
Very simple, just detect \n and replace it with <br/>
jQuery("#memorize-form").submit(function(e){
e.preventDefault(); //prevents form submit
e.stopImmediatePropagation(); //prevents form submit
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
//recommended way
if(result.match(/[^\r\n]+/g)){ //check for \n and replace it with <br>
result = result.replaceAll('\n','<br/>');
//result = result.replace('\r','<br/>'); handle \r if needed
}else{
//not recommended way
//check for . `fullstops` and add a br.
//if(result.includes('.')){
// result = result.replace('.','<br/>');
//}
}
jQuery("#result").html(result);
});
Tested code!

Convert percentage symbols to u+hex (javascript)

I need to replace decoded string which has percentage symbols to U+hex.
String:
"text=%F0%9F%98%8A&id=60&tags=";
What I need:
change %F0%9F%98%8A to 'U+1F60A' or 1F60A (globally), according to http://unicode.org/emoji/charts/full-emoji-list.html.
For 1f60a:
var c = decodeURIComponent("%F0%9F%98%8A").codePointAt(0).toString(16);
Note that \u1f60a wont work in JS (although it will as an HTML entity), you need 2 codepoints; c.charCodeAt(0).toString(16) & c.charCodeAt(1).toString(16)
var message = "This is my message %F0%9F%98%8A and I love emojis!";
$("p").text(decodeURI(message));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
var message

How to insert a line break in createTextNode

For a little program that outputs some XML Code in a p element I need to have some line breaks in the output.
In the last week I tried a lot of things like document.createElement("br"); or inserting escape character \n or unicode whitespace-character \u000A but nothing worked.
My output now:
<viva:form rdf:parseType="Resource"> <viva:title>55</viva:title>
I need it that way:
<viva:form rdf:parseType="Resource">
<viva:title>55</viva:title>
My code:
var vivaTitle;
function elementeAbrufen() {
vivaTitle = document.getElementById("inputVivaTitle").value;
var p = document.createElement("p");
var t = document.createTextNode(headErzeugen());
p.appendChild(t);
document.body.appendChild(p)
}
function headErzeugen() {
// insert unicode lf
var lf = "\u000A";
var xmlHeadStruktur = "<viva:form rdf:parseType=\"Resource\">";
var xmlHeadTitle = "<viva:title>" + vivaTitle + "</viva:title>";
return xmlHeadStruktur + lf + xmlHeadTitle
}
<p id="vivaTitle" title="">viva:title:
<input type="text" id="inputVivaTitle" value="">
<button onclick="elementeAbrufen()">send</button>
I'm thankfull for every help.
Cheers, Didier
Using \n works fine. Here's a jsfiddle:
https://jsfiddle.net/Lftqy9b0/1/
var text = document.createTextNode("Hello\u000aWorld");
document.body.appendChild(text);
document.body.style = "white-space: pre;"
'\n', '\u000a', etc. should all be valid, but I recommend using '\n'. Most people will recognize it better.
The reason this isn't working for you is that HTML collapses all whitespace. So even though the text node DOES contain a newline, it's just the same as a newline typed into HTML (those are text nodes too.)
You can see in the above snippet that I included a 'white-space: pre;' rule. This causes it not to collapse whitespace. See here for more options:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
If you're formatting raw text for display like this, that's probably the easiest way. Of course, you should put the white-space rule in a separate css file.
Does this work?
var t = document.createTextNode(headErzeugen() + '<br />');

Get String from the text box and apply to string properties

I have added one text box . I am getting the text entered text box like :
var text = document.getElementById("textarea").value;
then by using split function I am getting one particular String from say first string from the text . And tried to apply string properly on that like :
var split = text.split(" ");
var word = split[0];
word.italics();
then I formed text again with changed properties of first string and reassigned it to the text box
document.getElementById("textarea").value = text;
but those string properties are not applying to the word . same issue with all string properties like font color ,link etc . I dont know whats wrong I am doing ?
You cannot format text in a textbox
Try
document.getElementById("someContainerLikeADivOrSpan").innerHTML=text
For example
Live Demo
window.onload=function() {
document.getElementById("text").onkeyup=function() {
var text = this.value;
var split = text.split(" ");
var word = split[0];
document.getElementById("output").innerHTML=word.italics();
}
}
using
<textarea id="text" placeholder="type some words"></textarea>
<span id="output"></span>
You should use a div,span or p element to get the italics word. Try this,
HTML
<textarea id="textarea">test the italics now.</textarea>
<div id="div"></div>
SCRIPT
text=text.replace(word,word.italics());// replace the first word with italics
document.getElementById("div").innerHTML = text;// use div not textarea
Demo

Categories

Resources