base on the following string
...here..
..there...
.their.here.
How can i remove the .
on the beginning and end of string like the trim that removes all spaces, using javascript
the output should be
here
there
their.here
Use the trim() method to remove the line breaks from the start and end of a string, e.g. str. trim() . The trim method removes any leading or trailing whitespace from a string, including spaces, tabs and all line breaks.
String strip() in JavaScript We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string.
To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .
The RegExp \r Metacharacter in JavaScript is used to find the carriage return character (Carriage return means to return to the beginning of the current line without advancing downward). If it is found it returns the position else it returns -1.
These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg
:
Inside /()/
is where you write the pattern of the substring you want to find in the string:
/(ol)/
This will find the substringol
in the string.
var x = "colt".replace(/(ol)/, 'a');
will give you x == "cat"
;
The ^\.+|\.+$
in /()/
is separated into 2 parts by the symbol |
[means or]
^\.+
and\.+$
^\.+
means to find as many .
as possible at the start.
^
means at the start; \ is to escape the character; adding+
behind a character means to match any string containing one or more that character
\.+$
means to find as many .
as possible at the end.
$
means at the end.
The m
behind /()/
is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.
The g
behind /()/
is used to perform a global match: so it find all matches rather than stopping after the first match.
To learn more about RegEx you can check out this guide.
Try to use the following regex
var text = '...here..\n..there...\n.their.here.';
var replaced = text.replace(/(^\.+|\.+$)/mg, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With