Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Remove strings in beginning and end

Tags:

javascript

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
like image 385
Snippet Avatar asked Oct 02 '13 10:10

Snippet


People also ask

How do I remove the start and end of a string?

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.

How do you strip text in JavaScript?

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.

How do I remove a character from the end of a string in JavaScript?

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) .

What does \r do in JavaScript?

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.


2 Answers

These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:

  1. Inside /()/ is where you write the pattern of the substring you want to find in the string:

    /(ol)/ This will find the substring ol in the string.

    var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";

  2. The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]

    ^\.+ and \.+$

    1. ^\.+ 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

    2. \.+$ means to find as many . as possible at the end.

      $ means at the end.

  3. 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.

  4. 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.

like image 191
Archy Will He 何魏奇 Avatar answered Oct 13 '22 21:10

Archy Will He 何魏奇


Try to use the following regex

var text = '...here..\n..there...\n.their.here.';
var replaced =  text.replace(/(^\.+|\.+$)/mg, '');
like image 22
Arun P Johny Avatar answered Oct 13 '22 22:10

Arun P Johny