I have been working on this assignment where I have to make a prompt in which the visitor puts types in a string (or just any sentence for this matter) and afterwards the typed text needs to be shown on the page itself alongside with an indication in what line the first spacebar is implemented.
The problem however is that i need to put this in quote signs and since I am using a "+ script" in my Code, I cannot put it inside quotes.
Here is the code I am using:
<body>
<p id="Result"> </p>
<p id="First Spacebar"></p>
<script>
let string = prompt("Put text here");
const text = string;
document.getElementById('Result').innerHTML = "You said: " + string
document.getElementById('First Spacebar').innerHTML = "The first spacebar bevindt can be found in line: " + string.indexOf((" "));
</script>
</body>
Everything is working like it should, but i can't seem to get the " signs on each end of the string in the webpage version.
You can use template strings
<body>
<p id="Result"> </p>
<p id="First Spacebar"></p>
<script>
let string = prompt("Put text here");
const text = string;
document.getElementById('Result').innerHTML = `You said: "${string}"`
document.getElementById('First Spacebar').innerHTML = "The first spacebar bevindt can be found in line: " + string.indexOf((" "));
</script>
</body>
You can either escape the " that are meant to be displayed ("..\""), or , you can enclose your strings in single quotes ' and freely use double quotes " inside it:
let string = prompt("Put text here");
const text = string;
document.getElementById('Result').innerHTML = 'You said: "' + string + '"';
document.getElementById('First Spacebar').innerHTML = "The first spacebar bevindt can be found in line: " + string.indexOf((" "));
<p id="Result"></p>
<p id="First Spacebar"></p>
With ES6 template literals you can do it like this:
`You said: "${string}"`
Old style, you can leverage the fact that you can use either " or ' as outer quotation marks:
'You said: "' + string + '"'
Here are 2 ways:
document.getElementById('Result').innerHTML = 'You said: "' + string + '"'
(this uses both kinds of quotation marks so one can be used inside strings)
document.getElementById('Result').innerHTML = "You said: \"" + string + "\""
(this uses the escape character, '`', to indicate quotation marks that should be used as normal characters instead of surrounding strings)
You can use javascript escape codes. You can find an easy conversion table for these escape codes here.
The javascript escape code for " is \u0022.
A full script example:
<body>
<p id="Result"> </p>
<p id="First Spacebar"></p>
<script>
let string = prompt("Put text here");
const text = string;
document.getElementById('Result').innerHTML = "You said: \u0022" + string + "\u0022";
document.getElementById('First Spacebar').innerHTML = "The first spacebar bevindt can be found in line: " + string.indexOf((" "));
</script>
</body>
Related
Im trying to save some HTML in a JS variable by using the backtick formatting however is it possible to preserve the HTML variable according to the following example
var msg = "This is a test" + "\n" + "Test"
Im attempting to store this variable as a HTML paragraph while keeping the linebreaks
var emsg = '<p style="white-space: pre-wrap;"><\"{msg}"\</p>'
But when sending that content in an email to myself (Using Emailjs) I get the following
<"{msg}"
Any clue what I'm doing wrong? Thanks!
You are using single quotes ('), not backticks (`)
Placeholders in template literals are indicated by a dollar sign ($), which you are missing.
var msg = "This is a test" + "\n" + "Test"
var emsg = `<p style="white-space: pre-wrap;"><\"${msg}"\</p>`
console.log(emsg)
You could go with template literals like #spectric showed.
or you can go with simple quote using + to seperate it with msg variable
var msg = "This is a test" + "\n" + "Test";// V V
var emsg = '<p style="white-space: pre-wrap;"><\"'+msg+'"\</p>';
console.log(emsg);
as described + removing the extra <\" and "\ probably
var emsg = <p style="white-space: pre-wrap;">${msg}</p>
I have written some code that works fine but I am trying to make a space between the strings.
The code I have is:
<html>
<head>
<title> Concatenating Strings </title>
</head>
<body>
<script type = "text/javascript">
var greetingString = "Hello";
var myName = prompt ("Please enter your name","");
var concatString;
document.write(greetingString + "" + myName + "<br>");
concatString = greetingString + "" + myName;
document.write(concatString);
</script>
</body>
</html>
At the moment the script shows HelloMichael, I am wanting it to show Hello Michael. Can someone please advise me on how I can do that?
To insert a space character, simply insert a space character. For example:
greetingString + " " + myName
There's no space in your current output, because "" doesn't have a space in it.
put a space between hello and michael like this:
concatString = greetingString + " " + myName; //notice the space in the string
concatString = greetingString + " " + myName;
Simply change your "" to " ", the second has a space in it.
Hi I am having the string which contains html content and I want use javascript to replace the tag <p class="MsoNormal"> with '' empty space and i want to replace corresponding closing tag </p> with <br> tag in that string.
If I use
first line:
str=str.replace(/<p class=\"MsoNormal\">/g,'');
second line: str=str.replace(/<\/p>/g,'<br>');
All the closing </p> tag get remove .But i want to replace the closing </p> tag which has the opening tag of "<p class="MsoNormal">".
The first line of script is okay of me .What should i use to replace that corresponding closing tag in the second line.
Check this: Output is what I got from your question is to replace with Empty String
var replaceTag = function(str, replaceTagString, endTagString) {
var str = '';
while(str.indexOf(replaceTagString) != -1) {
//search for </p> after my matched String
var indexOfClosingTag = str.indexOf(endTagString, str.indexOf(replaceTagString))
//Replace </p> using Substring
str = str.substr(0,indexOfClosingTag) + "<br>" + str.substr(indexOfClosingTag + endTagString.length,k.length)
//Replace your main String
str = str.replace(replaceTagString,'')
}
return str
}
var k = "<p class='MsoNormal'>something</p><p>other p tag</p><h1>I am h1</h1><p>Hello p</p><p class='MsoNormal'>Replace My Tag too</p>"
replaceTag(k, "<p class='MsoNormal'>", "</p>")
Output:
"something<p>other p tag</p><h1>I am h1</h1><p>Hello p</p>Replace My Tag too"
Concept:
string.indexOf(searchvalue,start)
Start searching for End of the Tag (P) after my current matched string position
Define a function yourself like this-->
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
And use it like this:
str = str.replaceAt(3, "</p>");
Ok, I'm having a huge problem, and I've been looking for days about how to do this. Either I can't read well enough to understand it, or I'm stupid. I'm not sure what it is yet. I'll be honest and say that this is homework, but I've been struggling with this for 3 days now, and as its an online class, I can't go see my instructor and ask him what I'm doing wrong. I have emailed him, but his help is limited and vague, and I cannot figure this out. Anyway, to the point. I want to add HTML to the text that's going to be displayed in a new window using a JavaScript function. Here's the basics of what I have.
function myWindow(){
var pageContent, pageTitle;
pageTitle = document.write("Selected Image Preview");
document.write.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>"Name of Image"</h3>";
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
pageContent += "</strong></body></html>";
}
Now, I have no idea what I'm doing wrong, considering I've read almost everything that I could find, searched all over this site, as well as dozens of others. I've tried the W3 schools, and some site that looked like it was last updated in 2001, and my book has absolutely NO examples of HTML being used inside the function (it's a javascript book, so the HTML help is very limited). Starting at the top, it tells me that "Uncaught SyntaxError: Unexpected token ILLEGAL junk.html:16" on the script line. Then it won't load the rest of the page. If I comment that out, it tells me that '<h3>' is an unexpected identifier, and it just keeps going. There's always something wrong and if I comment out the lines that give errors, then there's nothing left. Please help me figure out what I'm doing wrong. And if it's necessary, I am calling the function onload with the <body onload="myWindow();"> tag.
P.S. Please don't kill me if I've formatted this incorrectly. I did read the directions, and tried to format this as neatly as possible.
The biggest problem was that the closing </script> tag in the line with the call to alert() terminated the script, even though it was within a string literal. See the link in my comment to your original post. There were some other problems with quotes, and if a teacher is really teaching the <font> tag in 2014, I think I should track him down and throw up in his lap.
Note that the slash in </script> and the embedded double-quotes are now escaped with backslashes. That's the biggest change. Also, the function now returns the computed value so it can be used.
This code goes through a JavaScript console clean. It doesn't open any new windows, and it doesn't deal with the "style" line, which I couldn't figure out.
function myWindow(){
var pageContent, pageTitle;
pageTitle = "Selected Image Preview";
// document.write.style.textAlign="center"; // WTF?
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)<\/script>";
pageContent += "</head>";
pageContent += "<body style=\"text-align: center;\">";
pageContent += "<h3>Name of Image</h3>";
pageContent += "<strong>" + "<font color= \" violet \">\"Here is the image you selected. \"</font>";
pageContent += "</strong></body></html>";
return(pageContent);
}
I've edited the code. The <h3> line was within the head of the document, now fixed, and I added a style attribute to <body> based on your remark about wanting text centered.
Ok, your code contains errors, because you need to learn how to work with strings and quotes and how to escape quotes.
var str1 = "qwe";
var str2 = "asd";
var str3 = str1 + str2; // will be qweasd
var str3 = str1 + '1111' + str2; // will be qwe1111asd
var str3 = str1 + 'z"1"' + str2; // will be qwez"1"asd
var str3 = str1 + "z\"1\"" + str2; // will be qwez"1"asd. There is no difference if you use double quotes or single. If you use single quotes, all single quotes in the string must be escaped with backslash and opposite with double quotes
// and the same with single quotes:
var str3 = str1 + 'z\'1\'' + str2; // will be qwez'1'asd
also, you are using document.write function, which overrides the content of current page, but you need a new window, which is why we should use function window.open which returns a new window handler. We save it into OpenWindow variable and then we apply our content using OpenWindow.document.write passing our string pageContent as a first parameter
and the correct code:
function myWindow(){
var pageContent, pageTitle;
document.title = "Selected Image Preview";
document.body.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>Name of Image</h3>";
pageContent += '</head><body align="center"><strong><font color="violet">Here is the image you selected.</font>';
pageContent += "</strong></body></html>";
var OpenWindow = window.open('#','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(pageContent);
}
pageContent += "<h3>"Name of Image"</h3>";
You don't need quotes around name of image. The entire line should be treated as a String.
pageContent += "<h3>Name of Image</h3>";
Basically, anything in HTML tags doesn't need quotes unless you intend for quotes to appear.
For this line:
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
You should use single quotes.
pageContent += "</head><body align='center'><strong>" + "<font color='violet'>Here is the image you selected. </font>";
You should be able to fix the rest of your HTML, keeping in mind single quotes for attributer, no quotes for content.
As to the HTML itself, it should look like this to follow at least intended standards. You should move most of the styles eventually to CSS.
<html>
<head>
<title>Selected Image Preview</title>
<script>// your script here </script>
</head>
<body>
<div align='center'>
<!-- your content here -->
</div>
</body>
I'm trying to fix an inline javascript snippet with reg ex to be rewritten on an input field.
I have single quotes that wrap the inner double quotes and I want to convert the inner quotes to be single instead of double but I only want to convert them when the code appears as nested quotes.
Right now I'm doing the conversion for all instances of the quote which works but I might run into another problem. I'll attach my code below.
JavaScript
$(document).ready(function() {
$('.submit').bind('click', function(e) {
var yourstring = $("textarea").val();
yourstring = yourstring.replace(/'/g, "''");
yourstring = yourstring.replace(/"e;/g, "\"");
yourstring = yourstring.replace(/&lquote;/g, "\"");
yourstring = yourstring.replace(/&rquote;/g, "\"");
yourstring = yourstring.replace(/"/g, "\"");
yourstring = yourstring.replace(/“/g, "\"");
yourstring = yourstring.replace(/”/g, "\"");
yourstring = yourstring.replace(/"/g, "\"");
alert(yourstring)
});
});
HTML
<textarea style="width:400px;height:300px;">
function('');
<a onclick="$(".text").append('test');">Click Me</a>
<br/>
&lquote;test quotes&rquote;
" generic quotes "
</textarea>
<input type="submit" class="submit">
To be more specific I'm trying to get
<a onclick="$(".text").append('test');">Click Me</a>
To look like
<a onclick="$('.text').append('test');">Click Me</a>
The example provided does not seem to have anything to do with the database but a problem with the JavaScript code within the onclick attribute. That code actually doesn't have a valid syntax, but my guess is that you are trying to build some sort of editor for HTML code.
If you decide not to follow the recommendations in the comments above (which I agree with), to answer your question, here's an option for removing double quotes for text already surrounded by them:
var s = "<a onclick=\"$(\".text\").append('test');\">Click Me</a>";
var re = /"(.*)"/g;
var r = s.replace(re, function($0, $1) { return '"' + $1.replace(/"/g, "''") + '"'; });
console.log(r);