Delete parts of a string using javascript

I have a somewhat strange situation where I need to fix a mistake on a website where, when creating a line (dynamically), it adds 5 spaces before the line and 5 spaces after the line. Obviously, the best thing would be to fix the end code and get rid of these spaces ... In short, I cannot, and I have to do it with javascript. I'm not quite sure how to do this, but this is what I was thinking about.

<!--Dynamically generated string including spaces added in backend-->
<span id="balance">     245.34     </span>

My idea was this: javascript

function removespace()
{
  var oldString = document.getElementById('balance');
  var newString = (THIS IS WHERE I AM STUCK... I NEED TO REMOVE THE SPACES);
  document.getElementByID('balance').innerHTML = newString;
}

Does anyone have any suggestions? Thank!

ALSO FORGET TO THE MENU: I cannot use javascript libraries such as prototype or jquery.

Edit: I still have this ... but it doesn't seem to work:

<span id="balance">     $245.00     </span>

 <script>
 function removespace()
 {
   var oldString = document.getElementById('balance');
   var newString = oldString.trim ();
   document.getElementByID('balance').innerHTML = newString;
 }

 String.prototype.trim = function() {
 return this.replace(/^\s+|\s+$/g,"");
 }
 </script>

here is the solution i used ... i finished it before i saw other updates ... but everyone was very helpful

function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
 }
 var oldString = document.getElementById('balance').innerHTML;
 var newString = trim(oldString);
 document.getElementById('balance').innerHTML = newString;
+3
6

JavaScript trim(). :

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

:

var newString = oldString.trim ();

- ( google "javascript trim" )

( ):

var oldString = document.getElementById('balance');

var oldString = document.getElementById('balance').innerHTML;

document.getElementByID('balance').innerHTML = newString;

document.getElementById('balance').innerHTML = newString; // notice the lower case d

removespace - ( , ):)

+8

.

var elem = doc.getElementById('balance');
var oldString = elem.innerHTML;
elem.innerHTML=oldString.(/^\s+|\s+$/g,"")

- ?

: yep, , 1:)

0

-

str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "");
0

trim(),

var newString = oldString.trim();

:

var newString = oldString.replace( "," ");

-1
source

with jQuery it is simple:

var newStr = jQuery.trim(oldStr);
-1
source

If the balance should be double, you can convert it to a string:

var c = '1234';
d = c * 1;

then return to the line if necessary:

d = c.toString();
-1
source

Source: https://habr.com/ru/post/1776701/


All Articles