Using negative conditions, how to remove whitespaces except line and paragraph breaks - javascript

One simple way to remove whitespaces in my case is to do like this -
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
input.value = input.value
.replace(/\t{1,}/g, "")
.replace(/\n{3,}/g, '\n\n')
.replace(/ {1,}/g, ' ')
.replace(/^ /gm, '')
.replace(/ $/gm, '')
.replace(/^\n{1,}/g, '')
.replace(/\n{1,}$/g, '');
}
</script>
However I'm trying to achieve the same objective with negative condition. That is by using minus or something like that. As i'm new to js, i'm not familiar with negative conditions. So can anyone tell me how to use negative condition in this case. The code should look something like this -
function whitespaces() {
var input = document.getElementById("thetext");
input.value = input.value.replace(all whitespaces [\s] minus linebreak [\n] and paragraph breaks [\n\n])
}

SOLUTION 1
You can use the following regular expression to match all whitespace characters except newlines.
[^\S\r\n]
That is, not-not-whitespace (the capital S complements) or not-carriage-return or not-newline. Distributing the outer not (i.e., the complementing ^ in the character class) with De Morgan's law, this is equivalent to “whitespace but not carriage return or newline.” Including both \r and \n in the pattern correctly handles all of Unix (LF), classic Mac OS (CR), and DOS-ish (CR LF) newline conventions.
From this stackoverflow answer.
SOLUTION 2
In javascript you can also use a replacer function to check each match and return the replacement string only if it meets certain conditions. The replacer function here checks for each whitespace whether it is a line break.
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
var inputVal = input.value;
inputVal = inputVal.replace(/\s/g, function(match){
return match === '\n' ? match : '';
});
input.value = inputVal;
}
</script>
SOLUTION 3
Another possible solution is to first replace all the paragraph breaks and line breaks by some bogus text (without whitespaces). Then do the whitespace replacement. After that convert the bogus texts back to paragraph and line breaks. (Note that since paragraphs are double line breaks, you do not need the line with the paragraph break replacement.)
<textarea id="thetext" lines="8" style="width: 100%; height: 8em;">
hello, how are you
i'm fine
And i hope the same from you
</textarea><br>
<button onclick="whitespaces()">Vanish</button>
<script>
function whitespaces() {
var input = document.getElementById("thetext");
var inputVal = input.value;
inputVal = inputVal.replace(/\n\n/g, "somebogustextforparagraphbreaks");
inputVal = inputVal.replace(/\n/g, "somebogustextforlinebreaks");
inputVal = inputVal.replace(/\s{1,}/g, "");
inputVal = inputVal.replace(/somebogustextforparagraphbreaks/g, "\n\n");
inputVal = inputVal.replace(/somebogustextforlinebreaks/g, "\n");
input.value = inputVal;
}
</script>

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.

Remove all tags in html string except <a>

I'v got some html which I must clear from all tags except one concrete <a> with known class.
Here is the html:
var string = '<span class="so_sentence"><span> Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a></span></span>';
I have JQuery attached, so I get the jQuery object of the string.
var html = $(string);
Now I have to clear the string from all the span and probably other tags, except this <a>:
<a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>
So my final string should be:
'Some text <a class="so_footnote-ref" href="#footnote-104008-4" id="footnote-104008-4-backlink">[1]</a>'
Also it must be possible to call this function on the result, so it must be of appropriate type:
function _trim(string){
return string.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
}
Try this:
$(string).find(':not(a)').contents().unwrap()
This will vorky with every piece of html code.
Example: http://jsfiddle.net/E3RWL/1/
Here's a function I found for you:
You can read more about this at: http://phpjs.org/functions/strip_tags/
Javascript:
var ret = strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
// returns: 'Kevin <b>van</b> <i>Zonneveld</i>'
function strip_tags (input, allowed) {
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}

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.

Get values from TEXTAREA

<textarea name="test" id="text">
text
area
one one
two
break above
last
</textarea>
<span id="getvalues">get values</span>
$("#getvalues").click(function(){
})
How can i get all values from this textarea from each line to javascript array?
This should:
ignore whitespace - trim
ignore white break
Next i would like make:
$.each(textareavalues, function(index, value) {
console.log('#' + value + '#');
});
This should show me:
#text#
#area#
#one one#
#two#
#break above#
#last#
LIVE EXAMPLE: http://jsfiddle.net/BW8Z2/1/
When you say "ignore white space - trim", you mean "ignore leading and trailing white space on a line, but keep internal white space"? And "ignore white break" means "ignore lines with just white space"?
Something like this:
$("#getvalues").click(function(){
var lines = $("#text").val()
.replace(/\n\s*\n/g,"\n")
.replace(/^\s+|\s+$/gm,"")
.split(/\n/);
$.each(lines, function(i, val) {
console.log("#" + val + "#");
});
})
$("#getvalues").click(function(){
var $textareavalues = $("#text").val();
var x = $textareavalues.split('\n');
$.each(x, function(index, value) {
var text = $.trim(value);
if(text !== "")
console.log('#' + text + '#');
});
});
This will get you started:
var textareavalues = $('textarea').val().split('\n');
you can find how to trim strings and how to exclude empty items in an array in JavaScript from other questions on StackOverflow.

Categories

Resources