Home > Web Front-end > JS Tutorial > How to remove spaces from string in jquery?

How to remove spaces from string in jquery?

青灯夜游
Release: 2020-11-30 14:22:17
Original
6276 people have browsed it

Jquery method to remove spaces from strings: 1. Use the replace function with regular expressions to find spaces in the string, and replace the spaces with the empty character ['']; 2. Use [$. trim] function to remove spaces at the beginning and end of a string, syntax [$.trim(str)].

How to remove spaces from string in jquery?

Related recommendations: "jQuery Tutorial"

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, This method works for all brands of computers.

Method 1: Use replace() with regular expressions

Remove all spaces [The spaces at both ends include spaces in the middle of the string]:

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

Remove double spaces:

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

Remove left spaces:

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

Remove right spaces:

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

Method 2: $.trim() function

$.trim() function is used to remove whitespace characters at both ends of a string.

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.

Grammar

$.trim( str )
Copy after login

Example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
	
<pre id="original">

<script>
$(function () { 
	var str = "         lots of spaces before and after         ";
	$( "#original" ).html( "Original String: &#39;" + str + "&#39;" );
	$( "#trimmed" ).html( "$.trim()&#39;ed: &#39;" + $.trim(str) + "&#39;" );
})
</script>
 

Copy after login

For more programming related knowledge, please visit:Programming Course! !

The above is the detailed content of How to remove spaces from string in jquery?. 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