I have a javascript method which is receiving a UTF-8 encoded string (ViewBag.errorText), and uses this as a parameter to a new function.
The problem is that the text displayed in show_error_dialog is displaying the html escaped characters (æø etc') and not the intended ("æåø" etc.).
I presume the problem is the enclosed <text> tags but can't seem to get around this.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#ViewBag.errorText');</text>
}
}
</script>
I think all Razor-inserted text is HTML-encoded by default. Use Html.Raw() to pass the string unencoded.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#Html.Raw(ViewBag.errorText)');</text>
}
}
</script>
Use:
#Html.Raw(Ajax.JavaScriptStringEncode(Model))
to safely insert values into javascript
just use javascript escape function:
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}
I'm not sure but i think there was unescape() function with js. Try to pass your text with it. It might help
Related
I am working on a React app which needs json-ld schema to be defined. I get the schema string through an API and need to add the appropriate script tag to my page.
My schema string looks something like this:
[{"#context": "http://schema.org"}]
I expect this to be translated to:
<script type="application/ld+json">
[{"#context": "http://schema.org"}]
</script>
However, I am having trouble dealing with the double quotes, as these get converted to html equivalent - "
This is how my code looks like:
schemaString = "[{\"#context\": \"http://schema.org\"}]";
render() {
return (<div>{schemaString &&
<script type="application/ld+json">
{schemaString}
</script>}
</div>)
}
The html generated is:
<div>
<script type="application/ld+json">
[{"#context": "http://schema.org"}]
</script>
</div>
Any pointers on what I am missing here? Thanks!
Am I late? :) Make sure you place the script tag content by dangerouslySetInnerHTML property. Also, don't forget to convert default object into proper JSON by JSON.stringify() method.
Like this:
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(yourSchemaObject) }}
/>
);
schemaString = [{ "#context": "http://schema.org" }];
render() {
return (
<div>
{schemaString &&
<script type="application/ld+json">
{JSON.stringify(schemaString)}
</script>
}
</div>)
}
What can I do to attain the below thing... The argument generated is bit weird!
function function1(argument1,argument2)
{
if argument1 = "
") do something;
}
"argument1" and "argument2" are generated by the CMS. I can't do anything with those contents.
Either it will generate:
<script type='text/javascript'>
document.write(function1("argument1","argument2"));
</script>
OR
<script type='text/javascript'>
document.write(function1("
","argument2"));
</script>
You can use String.prototype.trim():
function function1(argument1,argument2)
{
if(argument1.trim() == ''){
// do something
}
}
If you're worried about old browsers, you can implement the trim function yourself, see this question.
<!DOCTYPE html>
<html>
<head><script type="text/javascript">
function onPaste(eve) {
try {
var txt = e.clipboardData.getData('text/plain');
alert(txt);
} catch (err) {
}
} </script> </head><body>
<textarea cols=60 name="inputUsaaNum" onpaste="onpaste(event);"></textarea></body></html>
please help to validate the clipboard data from text area, i need to identify the whaether it has any spacial character and also i want to delimit the values with help of carriage return('\r'), please help????
According to your last comments you want something like this:
txt.replace(/[^1-9_\t ]/g,'').replace(/[\t]/g,'\r');
This will first replace everything that is not 1 to 9 or _ or space or a tab with '', then it will replace all tabs with \r. Why did I include tabs, well the asker specifies excel data.
Good Luck!!
Update for your comments:
if (txt.match(/[^1-9_\t ]/g)) {
alert('error');
} else {
txt=txt.replace(/[\t]/g,'\r');
}
Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}
I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "<")
.replace(/>/g, ">")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN