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

How to remove spaces from string in jquery?

青灯夜游
青灯夜游Original
2020-11-24 11:25:036227browse

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,'');

Remove double spaces:

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

Remove left spaces:

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

Remove right spaces:

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

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 )

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>
 

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!

Statement:
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