Removing whitespace in textarea ignored by jQuery.trim() - javascript

I have a <textarea> which contains a text called by php. The text contains an ID of the user, so it's for every user different. However, the html looks always like this:
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
How do I remove these whitespaces. I have tried multiple trim suggestions or Regex approaches on SO, but none of them are working. The textarea cannot be changed into a div or p.
Update:
Regex is somehow ignored, but the below answer gave the outcome:
$("#text").val((i, v) => '${v.slice(1, -1).trim()}');

Use regex pattern /\s{2,}/g in .replace() that match multiple spaces and remove them from string.
$("#text").val((i, v) => v.replace(/\s{2,}/g, ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
Also you can remove " from start and end of string using String.slice() and then remove space using .trim(). At the end wrap string with ""
$("#text").val((i, v) => `"${v.slice(1, -1).trim()}"`);

You can use a regex to remove quotes and spaces
$("#text").val($("#text").val().replace(/^"\s+(.*?)\s+"$/,"$1"));
console.log(">"+$("#text").val()+"<")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>

Related

Create a line break in the text inside span

I am using the following HTML in the application:-
<span style="display:inline-block;white-space: pre-line">I would like to discuss this: {"incidentId":"TG00040","desc":"Patient Details","reportdetails":"Patient Name:Bhawana \n Grade:10th \n Teacher:Meeta"}</span>
But am not able to create line breaks in the text. I have also tried using \n,\r and br tag but nothing seems to break. The expected output is:-
I would like to discuss this: {"incidentId":"TG00040","desc":"Patient Details","reportdetails":"Patient Name:Bhawana Grade:10th Teacher:Meeta"}
If data displayed in span contain the character \n and you can't modify it before display it in dom
you can use a simple js function to replace all \n occurence by <br/>
var span = document.getElementById('my-data');
span.innerHTML = span.innerHTML.replaceAll('\\n', '<br/>');
<span id="my-data">I would like to discuss this: {"incidentId":"TG00040","desc":"Patient Details","reportdetails":"Patient Name:Bhawana \n Grade:10th \n Teacher:Meeta"}</span>
just be careful to mastered dom modification when you replace innerHTML. here there is no risk but if you have based replace on user input you can have xss issue
use <br> instead of \n. Do you want output like this with a line break?
<span style="display:inline-block;white-space: pre-line">I would like to discuss this: {"incidentId":"TG00040","desc":"Patient Details","reportdetails":"Patient Name:Bhawana <br> Grade:10th <br> Teacher:Meeta"}</span>

How can i remove all characters started with # from inside a div element using jquery or javascript?

As mentioned on the title here is a div element
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
I use this jquery code to get the whole content of the div element and store it in a variable:
<script type="text/javascript">
var $itemdesc = $('#description').text();
</script>
but how can next remove the content that start with the # hashtag?
Assuming you want to remove up to the end of the line that contains the #, use replace with this regex #.*\n:
var $itemdesc = $('#description').text();
var $result = $itemdesc.replace(/#.*\n/g, '');
console.log($result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
And keep this as well.
# And remove this as well.
</div>
If the content is always the same structure - ie: text you want + '#' + text you dont want - then simply split the text content on the character and pass only the first portion to a variable.
let content = document.querySelector('#description').textContent.split('#')[0].trim();
console.log(content); // gives "This is an example text i wanna keep."
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
One way to do it would be to split the text based on the # character and just use the first element of the resultant array.
const text = document.querySelector('#description').innerHTML;
const split = text.split('#')
console.log(split[0].trim());
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
Another option would be to use regular expressions, like in this example: How to match "anything up until this sequence of characters" in a regular expression?.
You can do that with simple regex...
var $itemdesc = $('#description').text();
console.log($itemdesc.replace(/^#.*\n/gm, ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
This is an example text i wanna keep.
# And this is the text i want to remove.
This is an example text i wanna keep.
# And this is the text i want to remove.
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
You achieve this in one line with filter:
Split text by newlines
Filter every lines starting with anything but '#'
Concat back every lines
$('#description').text($('#description').text().split("\n").filter(x => !x.startsWith('#')).join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
Same solution without JQuery:
document.querySelector('#description').innerText = document.querySelector('#description').textContent.split("\n").filter(x => !x.startsWith('#')).join('\n');
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>
This code will also work with multi lines:
document.querySelector('#description').innerText = document.querySelector('#description').textContent.split("\n").filter(x => !x.startsWith('#')).join('\n');
<div id="description" class="bold">
This is an example text i wanna keep.
# And this is the text i want to remove.
This is an example text i wanna keep.
# And this is the text i want to remove.
</div>

Remove first line from Textarea

I have a tool that removes the blank lines from a confirmation (text) but for some reason there is a top line that is not being read as blank line and does not get deleted.
Currently my tool allows a person to paste text into the textarea then when "remove spaces & copy" button is clicked blank lines are removed and text is copied to the clipboard.
I want to keep the same function but somehow delete the first line either when text is entered into the textarea or when "remove spaces & copy" button is clicked.
<script>
function copyToClipboard(element) {
var text = $(element).clone().find('br').prepend('\r\n').end().text()
element = $('<textarea>').appendTo('body').val(text).select()
document.execCommand('copy')
element.remove()
}
</script>
<textarea name="mas" rows="100" rows="50" contenteditable="true" id="p20" class="content" onchange="this.value=this.value.replace(/[\n\r](?!\w)/gi,'');" style="height: 500px; width:800px;" type="text" data-bind="value: myValue, hasFocus: cleared"></textarea>
<!----------- BUTTONS ------------>
<div class="fixed">
<button onclick="copyToClipboard('#p20')" class="templateBtn">Remove Spaces & Copy</button>
<input type="button" data-bind="click: clearValue" value="clear" class="templateBtn" />
<script type="text/javascript">
var viewModel = {
myValue: ko.observable(''),
cleared: ko.observable(false),
clearValue: function() {
this.myValue('');
this.cleared(true);
}
};
ko.applyBindings(viewModel);
</script>
<!----------- END.BUTTONS ------------>
<div class="mas" id="hide" ></div>
<pre contenteditable="true" id="p20" class="templateText">
</div></div>
The regular expression [\n\r](?!\w) matches any CR or LF not followed by an alphanumeric or underscore character. So it can match the first of two line terminators in a row when replacing blank lines with the null string. '' It doesn't match a line terminator followed by a letter. Hence a line terminator at the beginning of text, followed by a word character, is left in place.
Blank lines defined as "Start of line, followed by zero or more whitespace characters not including line terminators, followed by end of line, followed by zero or more line terminators" can be matched by a multi line regular expression such as:
/^[ \f\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$[\n\r]*/gm;
where the first character set is that used for matching whitespace (\s) after removing the line feed and carriage return characters, and the $[\n\r]* component matches both line terminators and end of input. (Edited: a trailing blank line without a line terminator at the end is matched)
Try it below by entering lines and clicking outside the textarea element to trigger a change event:
function removeBlankLines( textArea) {
var blankLine = /^[ \f\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$[\n\r]*/gm;
textArea.value=textArea.value.replace(blankLine,'');
}
<textarea onchange="removeBlankLines( this)" cols="20" rows="8"></textarea>
This does not trim or remove spaces within non-blank lines. If you are still having trouble achieving what you wish to do, please update the question with text data used to produce the problem and detailed description of what you expected and what you got. Please remove the knockout code if it not related to the question (it doesn't appear to be).
Here is a quick fix you could use, perform a trim() on the replaced text:
<textarea name="mas" rows="100" rows="50" contenteditable="true"
id="p20" class="content"
onchange="this.value=(this.value.replace(/[\n\r](?!\w)/gi,'')).trim();"
style="height: 500px; width:800px;" type="text"
data-bind="value: myValue, hasFocus: cleared"></textarea>

Include space from input

My user wants an input field where he can enter a message, which I will then have displayed as a scrolling marquee across the page. He wants to be able to include empty spaces, for example,
"Employees please look up."
My textarea, when I get the text, doesn't notice the space. Any way to get that?
I know this is an odd request - google only tells me how to remove whitespace, not include it.
var text = $('textarea').val();
<textarea class='messageInput'></textarea>
I am pretty sure that you are getting the value with all the white-spaces right, the problem is in the displaying of the value in your (probably) custom div. The best way would be to set white-space: pre on that element which (as the option suggests) will preserve white-space. ;) Example:
<div id="foo" style="white-space: pre"><!-- insert text here --></div>
And ignore all the &nbps; suggestions which are essentially modifying the text content. CSS is the right way to do this!
You need to convert space characters into non-breaking spaces, which can be done using String.prototype.replace() with a regular expression:
$('#text').html($('textarea').val().replace(/ /g, '&nbsp'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='messageInput'>employees hello</textarea>
<p id="text"></p>
You need / /g so that it will match all spaces, not just the first one, which .replace(' '...) would do.
Note that smajl's suggestion is less invasive and probably better, but I'll leave this for posterity.
The spaces in the value are not ignored. It's that the browser by default "compresses" duplicate spaces. Use white-space:pre;
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
document.getElementById("button").onclick = function() {
var content = document.getElementById("input").value;
console.log(content);
document.getElementById("result").innerHTML = content;
}
#result {
white-space:pre;
}
<input type="text" id="input">
<button id="button">
TEST
</button>
<div id="result"></div>
EDIT: too late ;)

how to remove <textarea> whitespace

I want a <textarea>, as the one I'm writing in right now actually.
How do I make the textarea behave like this one? I want it to start at the beginning and not give me whitespace to erase when clicking in the middle of it.
HTML
<p>
<textarea class="noteToAdd">
</textarea>
</p>
Any ideas?
That what is between the start tag <textarea> and end tag </textarea> is it's value. Even whitespace is seen as 'value'. You probably have something like this: (note the whitespace)
<textarea>
</textarea>
So, to remove that, remove all whitespace and place the start and ending tag directly after each other.
<textarea></textarea>
Remove your whitespace between the textarea tag. Like as
<textarea></textarea>
Try this one :
<p>
<textarea class="noteToAdd">
</textarea>
</p>
Make sure there is no whitespace between your <textarea> and </textarea> tags, any whitespace here will show up in your text area.
More help is not possible without you providing the HTML/CSS.
Remove the extra white space in between the textarea opening and closing tags as they take up that space. You write your content inside <textarea></textarea>
<p>
<textarea class="noteToAdd"></textarea>
</p>

Categories

Resources