Tips trim in jquery like in php

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

Examples:

Remove the white spaces at the start and at the end of the string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.trim demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<pre id="original"></pre>
<pre id="trimmed"></pre>
<script>
var str = " lots of spaces before and after ";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" );
</script>
</body>
</html>

Demo:

Remove the white spaces at the start and at the end of the string.

1
$.trim(" hello, how are you? ");

Result:

1
"hello, how are you?"

Hope help you ūüôā

ref: https://api.jquery.com/jQuery.trim/

Str replace in jquery

Once I was trying to replace a character with another character in client side. I was trying to replace¬†space with dash and started with replace(‘ ‘, ‘-‘) method but I was not accepting the result. It was only working one time, I mean replace() method replaced only first character but not all.

The Problem

Problem is to replace all the related characters with a specific character. Here you will see how to replace space with dash or underscore character.

The Solution

You can use str.replace(/ /g, “-“) or str.split(‘ ‘).join(‘-‘) to achieve this. Let’s see this with a simple example.

Code

Use this simple code to replace space with dash. You can use any of the line to do your job.

    <script>
        $(document).ready(function () {
            var str = "John Sara Tom";
            alert(str.replace(/ /g, "-"));
            alert(str.split(' ').join('-'));
        });
    </script>
   // Output is John-Sara-Tom

Hope this helps you.

ref: http://dotnet-concept.com/Tips/2015/3/5798821/How-to-replace-Space-with-Dash-or-Underscore-in-JQuery