Reputation: 546
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()}');
Upvotes: 0
Views: 746
Reputation: 21489
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()}"`);
Upvotes: 1
Reputation: 178350
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>
Upvotes: 1