Home > Web Front-end > JS Tutorial > How to remove spaces in javascript

How to remove spaces in javascript

青灯夜游
Release: 2023-01-05 16:09:52
Original
23888 people have browsed it

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)".

How to remove spaces in javascript

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,"");
Copy after login

Remove two spaces:

str=str.replace(/^\s+|\s+$/g,"");
Copy after login

Remove left space:

str=str.replace( /^\s*/g, '');
Copy after login

Remove right spaces:

str=str.replace(/(\s*$)/g, "");
Copy after login

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) + "'" );
})
Copy after login

Output result

Original String: '         lots of spaces before and after         '
$.trim()'ed: 'lots of spaces before and after'
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template