Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the Trim () methods for native js to remove the space at the 2 end of the string

Shulou Source: shulou.com Published: 2022-06-03 06:21:38 11月08日 Update

Today, I will talk to you about the methods of native js to remove the space Trim () at the end of the string. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

When we use JavaScript to write scripts, we often encounter clearing the spaces on both sides of the string. It doesn't want other languages to have built-in method functions to handle. Js needs our own code to implement it. If you have used the jquery library, it provides the trim method.

Jquery library trim method

We can directly use:

Varcontent=$ ('# results') .val ()

If ($.trim (content) = =') {

Console.log ("Please enter content")

}

Use native js to implement trim functionality:

Method 1:

Functiontrim (str) {/ / remove str whitespace

Returnstr.replace (/ (^\ s *) (\ s $) / g, "")

}

Method 2:

Functiontrim (m) {

While ((m.length > 0) & & (m.charAt (0) = ='))

M=m.substring (1 ~ m. Length)

While ((m.length > 0) & & (m.charAt (m.length-1) = ='))

M=m.substring (0memm.futhmur1)

Returnm

}

Method 3:

/ / remove the space to the left of the string

FunctionlTrim (str)

{

If (str.charAt (0) = = "")

{

/ / if the first character on the left of the string is a space

Str=str.slice (1); / / remove spaces from the string

/ / this sentence can also be changed to str=str.substring (1 heroine str.length)

Str=lTrim (str); / / Recursive call

}

Returnstr

}

/ / remove the space to the right of the string

FunctionrTrim (str)

{

VariLength

ILength=str.length

If (str.charAt (iLength-1) = "")

{

/ / if the first character to the right of the string is a space

Str=str.slice (0recording iLengthmur1); / / remove spaces from the string

/ / this sentence can also be changed to str=str.substring.

Str=rTrim (str); / / Recursive call

}

Returnstr

}

/ / remove the spaces on both sides of the string

Functiontrim (str)

{

ReturnlTrim (rTrim (str))

}

After reading the above, do you have any further understanding of the native js Trim () method to remove the space at the second end of the string? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Spaces methods characters content strings right recursion code functions functions regular meetings times more knowledge articles scripts industries languages information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Huawei NVidia Docker Shulou Tech Info