Why javascript removes whitespace in String - javascript

I am trying to make hangman game and I want to display on the screen password like '_ _ _[space] _ _[space] _ _ _ _ _' . When I look at the variable it looks fine but it is instered into html without any space, what makes this application useless. Could you please help what should I change to see expected result? Thanks in advance
function hideWord() {
var password = '';
for (i = 0; i < word.length; i++) {
if (word.charAt(i) === ' ')
password += ' ';
else password += '_';
password += ' '
}
setHiddenWord(password);
}
function setHiddenWord(password) {
document.querySelector('div.letters').innerHTML += password;
}

Javascript is not removing the whitespace - The browser rendering of the HTML is. By default, HTML does not respect white space. If you want it to, put a white-space: pre; or white-space: pre-wrap; style on your element
In your CSS:
div.letters {
white-space: pre-wrap;
}

Related

How to add a new line to HTML text using JavaScript?

I am using this code which essentially types text onto the screen. I am unsure how to add a new line to the string which is being displayed.
I have already tried \n for those posting their answers. This does NOT work. A new line is not started in my HTML
Code:
var myString = "public class MyResume implements Resume{" +
/*this is where I want the new line*/ "...." ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
<div id="myTypingText"></div>
You can also use <br>.Just like"your string.<br> new line"
Here's an overly simplistic approach with full code. Use a tilde ~ and then watch for it in your frameLooper to insert a like this:
<html>
<body>
<div id="myTypingText"></div>
<script>
var myString = 'public class MyResume implements Resume{~....' ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
var char = myArray.shift();
if (char === '~')
{ document.getElementById("myTypingText").innerHTML += '<br/>'; }
else
{ document.getElementById("myTypingText").innerHTML += char; }
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
</body>
</html>
Simply adding <br> to myString doesn't work because you're inserting each character at one time. When a character gets added with innerHTML, JavaScript encodes it:
$('element').innerHTML += "<";
> "string<"
If you did this for each character in <br>, you'd end up with
>"string<br<"
You need some way to tell your script to add the entire element when you reach a "break character". You could use an uncommon character like a pipe | or you could add a method which looks ahead to make sure that the next few characters don't spell out <br>.
To add string to a new line, you need the \n in your string. For example:
var string = 'This is the first line \nThis is the second line'
console.log(string)
This would output
This is the first line
This is the second line
Why don't you just append ul>li or p to your text, something like this:
document.getElementById("myTypingText").innerHTML += "<p>" + myArray.shift() "</p>";
or
document.getElementById("myTypingText").innerHTML += "<li>" + myArray.shift() "</li>";
with:
<ul id="myTypingText"></ul>

How to Properly Add Double Quotes to a Textarea

I need a textarea to include a set of double quotes at the start and end of the textarea value. The below code works in that double quotes are added to the start and end of the field, but if the user enters text and then goes back to the field, multiple double quote sets can be added. How can I prevent this? A jQuery solution is also acceptable.
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function quotes(){
var quoteValueBefore = document.getElementById("quoteName").value;
var ensureQuotes = "\"" + quoteValueBefore + "\"";
document.getElementById("quoteName").value = ensureQuotes;
}
Check to see if the text already begins with a quote, and if it already ends with one. If either is missing, add it.
Also check that the length >= 2, otherwise " would pass the test (ends with a quote? check. begins with a quote? check.)
function quotes() {
var quoteValue = document.getElementById("quoteName").value;
if (!quoteValue.match(/^"/))
quoteValue = '"' + quoteValue;
if (!quoteValue.match(/"$/))
quoteValue += '"';
if (quoteValue.length < 2)
quoteValue += '"';
document.getElementById("quoteName").value = quoteValue;
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onChange="quotes();" autofocus></textarea>
function checkQuotes(id) {
str = document.getElementById(id).value;
if (str[0] != '"') {
str = '"'.concat(str);
}
if (str[str.length - 1] != '"') {
str = str.concat('"')
}
return str
}
function quotes() {
withQuotes = checkQuotes("quoteName");
document.getElementById("quoteName").value = withQuotes
}
<textarea name="quoteName" id="quoteName" style="width:100%" rows="4" onchange="quotes()">testing the quotes feature</textarea>
This snippet will check if the first character is a quote, if it isn't it will prepend it. It also checks if the last character is a quote, if it isn't it will append it. This probably isn't the most friendly UI solution, and I recommend either adding this through CSS if you're using it for display purposes, or using PHP or whatever you're doing for the backend form submission.

Unicode Character 'BULLET' in Titanium App

I have a problem with the BULLET character in my Android App developed with Titanium.
I have this part of code:
function getFormattedPizza()
{
var text = win.crust + ' pizza with:\n';
if (win.toppings.length == 0)
{
text += '• Plain (cheese pizza)\n';
}
else
{
for (var i = 0; i < win.toppings.length; i++)
{
text += '• ' + win.toppings[i] + '\n';
}
}
return text;
}
and in my app I see the string &bull ; Plain (cheese pizza), not an unordered list.
In that way I can show a dots list?
instead of &bull you can use the '\u2022'+'Plain (cheese pizza)', \u2022 is the unicode for bullet.
Samlple code :
var lbl = Ti.UI.createLabel({
text : '\u2022'+' HELLO'
});
win.add(lbl);
For more unicodes you can check this Link, or refer to this question.
Hope this will help you. :)

Most efficient way of converting plain text to HTML, Match or Regexp

I have a large text document filled with random words, urls, email-addresses etc. An example: "word 2014 john#doe.com http://www.example.com/ http://example.com/image.gif", but it could look differently, there could be linebreaks, multiple spaces, tabs etc. And the data could very fast become huge (it is a type of bookmarking service so data is arriving all the time in the form of images, text and hyperlinks).
Another example of content in the text document (the one I use for testing):
http://movpod.in/images3/MovPod-logo.png
https://dt8kf6553cww8.cloudfront.net/static/images/developers/chooser-drawing-vfln1ftk6.png
http://xregexp.com/assets/regex_cookbook.gif
asd asd ad feaf
apa
http
I want to wrap all these strings in tags, and be able to target out images, hyperlinks, emails and strings. I have tried different ways but unsure which is the best, and also, there is a RegExp I do not fully understand.
The end result should be:
<span>word</span>
<span>2014</span>
<a class="mail" href="mailto:john#doe">john#doe.com</a>
<a class="url" href="http://www.example.com/">http://www.google.com/</a>
<a class="img" href="http://example.com/image.gif">http://example.com/image.gif</a>"
Match. This approach is however not keeping the text order intact, but it works.
arr = data.split("\n");
for (i = 0; i < arr.length; i++)
{
arr2 = arr[i].split(' ');
for (j = 0; j < arr2.length; j++)
{
if (arr2[j].match(/(.gif|.png|.jpg|.jpeg)/))
{
ext = arr2[j].substr(-4);
ext = ext.replace(".","");
imgs += '<a class="img '+ext+'" href="'+arr2[j]+'">'+arr2[j]+'</a>';
}
else if (arr2[j].match(/(http:)/))
{
urls += '<a class="url" href="'+arr2[j]+'">'+arr2[j]+'</a>';
}
else
{
spans += '<span>'+arr2[j]+'</span>';
}
}
}
Regexp. I thought it would be possible to look for the inverse at exp_all, as in anything else but containing http. It does not however.
var exp_img = /(https?:\/\/([\S]+?)\.(jpg|jpeg|png|gif))/g,
exp_link = /([^"])(https?:\/\/([a-z-\.]+)+([a-z]{2,4})([\/\w-_]+)\/?)/g,
exp_all = /^((?!http).)*$/g;
text = data.replace(exp_all, '<span>$3</span>');
text = text.replace(exp_img, '<a class="img" href="$1">$1</a>');
text = text.replace(exp_link, '<a class="url" href="$2">$2</a>');
So, the best way of accomplishing this plain-text to HTML conversion would be appreciated. I would love if there was already some type of library for this. I was looking at Markdown but then I would still have to update the plain-text for the Markdown, so I guess not an option.
And if possible I would like to strip out "http://" and have it as clean and neat as possible.
Im making a few assumptions about your data (for example, that every entry is always there.) If that's true, then something like this should work fine:
<script>
var data = ['word\n 2014\t\t john#doe.com\n\n\n\n\n http://www.example.com/ http://example.com/image.gif apa http',
'fooo 2013 foo#bar.com http://www.blah.com/ http://blah.com/gif.gif asd asd ad feaf'];
function htmlify(string){
var elem = string.replace(/[^\w\s\/#:\.]/g,'').replace(/\s+/g, ' ').split(' ');
var result = [];
for (var i = 0; i < elem.length; i++){
if (elem[i].match(/http:/)) {
if (elem[i].substr(-4).match(/.gif|.png|.jpg|.jpeg/)){
result.push("<a class='img' href='" + elem[i] + "'>" + elem[i] + "</a>");
} else {
result.push( "<a class='url' href='" + elem[i] + "'>" + elem[i] + "</a>");
}
} else if (elem[i].match(/\w+#\w+\.\w+/)){
result.push("<a class='mail' href='mailto:" + elem[i] + "'>" + elem[i] + "</a>");
} else {
result.push("<span>" + elem[i] + "</span>");
}
}
return result;
}
var result = data.map(htmlify);
console.log(result);
</script>

space between words in JS

I have this JS code:
function myPopUp()
{
var y;
var name=prompt("Please enter your name"," הכנס את שמך");
if (name!=null)
{
y= ' How are you today?';
document.getElementById("popup").innerHTML = y;
var x="";
var time=new Date().getHours();
if (time<20)
{
x="Have a nice day" + name + '!';
}
else
{
x=' Great evening '+ name +' ! ';
}
document.getElementById("demo").innerText = x ;
}
}
with this HTML code:
<body>
<button onclick="myPopUp()" >לחץ כאן</button>
<p id="demo"></p>
<p id="popup"></p>
</body>
My question: When someone write their name there is no space between the words? How do I put a space between words in JS?
Thank you.
Looks like you just need a space after "day," so try this:
x="Have a nice day " + name + '!';
In HTML, extra white space is collapsed to a single space (ASCII 32) character.
If you MUST force a space, use the html identity which is a non-breaking space.
Better yet, use CSS to put margins around your element and make the spacing visual.

Categories

Resources