Javascript 删除开头和结尾的字符串

标签 javascript

基于以下字符串

...here..
..there...
.their.here.

我如何使用 javascript 删除字符串开头和结尾的 .,就像删除所有空格的 trim

输出应该是

here
there
their.here

最佳答案

这些是此任务的 RegEx 为 /(^\.+|\.+$)/mg 的原因:

  1. /()/ 中,您可以在字符串中写入要查找的子字符串的模式:

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

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

  2. /()/中的^\.+|\.+$|分隔成两部分> [意味着或]

    ^\.+ and \.+$

    1. ^\.+ 表示在开头尽可能多的找到.

      ^ 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 at the end.

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

  4. /()/ 后面的g 用于执行全局匹配:因此它会找到所有匹配而不是在第一个匹配后停止。

要了解有关 RegEx 的更多信息,您可以查看 this guide .

关于Javascript 删除开头和结尾的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19134860/

相关文章:

php - Jquery从元素获取id并包含在post中

javascript - 将 Handlebars 与 D3.js 结合使用

javascript - 如何在具有固定宽度和高度的可滚动 div 上创建模式覆盖?

javascript - 如何使用 JavaScript 读取位于 <html> 之外的 HTML 注释?

javascript - Bootstrap 3 Accordion 面板问题

javascript - 使用 Electron 在 app.asar 中包含额外文件

javascript - 在 Puppeteer 中使用伪类选择器评估类

javascript - 使用 .width() 返回未定义

javascript - 根据用户账户状态弹出

javascript - 如何在 Angular.js 中实现组