Javascript在开头和结尾删除字符串 [英] Javascript Remove strings in beginning and end

查看:968
本文介绍了Javascript在开头和结尾删除字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于以下字符串

  ...这里.. 
..来...
.their.here。

如何删除字符串的开头和结尾,如删除所有空格的修剪,使用javascript



输出应为

 这里

他们。


解决方案

以下是此任务的RegEx为 /(^ \。+ | \。+ $)/ mg 的原因:


  1. /()/ 内写下模式您要在字符串中找到的子字符串:


    /(ol)/ 这将在字符串中找到子字符串 ol


    var x =colt.replace(/(ol)/,'a'); 会给你 x ==cat;


  2. ^ \。+ | \。+ $ in /()/ 由符号<$分为2部分c $ c> | [表示或]


    ^ \。+ \。+ $





    1. ^ \。+ 表示在开始时尽可能多地找到


      ^ 表示开始时;是逃避性格;在字符后面添加 + 意味着匹配包含一个或多个字符的任何字符串



    2. \。+ $ 表示尽可能多地找到


      $ 表示结尾。




  3. 背后的 m / ()/ 用于指定如果字符串具有换行符或回车符,则^和$运算符现在将匹配换行符边界而不是字符串边界。


  4. /()/ g >用于执行全局匹配:所以它找到所有匹配而不是在第一场比赛后停止。


To了解有关RegEx的更多信息,您可以查看本指南


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

解决方案

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.

这篇关于Javascript在开头和结尾删除字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆