Home>Article>Web Front-end> How to remove spaces in javascript
How to remove spaces in JavaScript: 1. Use the replace() function and regular expressions. For example, the statement "str.replace(/\s /g,"")" can remove all spaces; 2. Use trim () function can remove whitespace characters at both ends of a string, the syntax is "$.trim(str)".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use the replace() function with regular expressions
Thereplace() method is used to replace some characters with other characters in a string, or replace A substring that matches the regular expression.
Let’s take a closer look:
Remove all spaces:
str=str.replace(/\s+/g,"");
Remove two spaces:
str=str.replace(/^\s+|\s+$/g,"");
Remove left space:
str=str.replace( /^\s*/g, '');
Remove right spaces:
str=str.replace(/(\s*$)/g, "");
Method 2: Use jQuery’s trim() function
$.trim() function is used to remove two strings whitespace characters at the end.
Note: The $.trim() function will remove all newline characters, spaces (including consecutive spaces) and tab characters at the beginning and end of the string. If these whitespace characters are in the middle of the string, they are retained and not removed.
Example:
$(function () { var str = " lots of spaces before and after "; $( "#original" ).html( "Original String: '" + str + "'" ); $( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" ); })
Output result
Original String: ' lots of spaces before and after ' $.trim()'ed: 'lots of spaces before and after'
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of How to remove spaces in javascript. For more information, please follow other related articles on the PHP Chinese website!