Using regular expressions in JavaScript to delete spaces in a string

Source: Internet
Author: User
Tags rtrim

Instance

The code is as follows Copy Code

<script>
var str= "yexj00";
Str=str.replace (/^s*|s*$/g, "");
alert (str);
</script>


Instance

Imitation RTrim:

The code is as follows Copy Code

<script>
var str= "yexj00";
Str=str.replace (/s*$/g, "");
alert (str);
</script>

Instance


The code and test code are as follows:

The code is as follows Copy Code
 < The script type= "Text/javascript" >
 //deletes white space characters on either side of the string.
 function Trim (str) {
  return str.replace (/^s+|s+$/g, ');
 } The
 //deletes the white space character to the left of the string.
 function LTrim (str) {
  return str.replace (/^s+/g, ');
 } The
 //deletes the white space character to the right of the string.
 function RTrim (str) {
  return str.replace (/s+$/g, ');
 }
 //The following is the test code
 var trimtest = "123456789";
There is a space before and after.
 document.write (' Length: ' +trimtest.length+ ' <br/> ');
//before use
 document.write (' LTrim length: ' +ltrim (trimtest). length+ ' <br/> ');
//Use LTrim after
 document.write (' RTrim length: ' +rtrim (trimtest). length+ ' <br/> ');
//After using RTrim
 document.write (' Trim length: ' +trim (trimtest). length+ ' <br/> ');
//after using trim
 </script>

The results of the test are as follows:

The code is as follows Copy Code

Length:11
LTrim length:10
RTrim Length:10
Trim Length:9

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.