在Javascript中左边修剪 [英] Left Trim in Javascript

查看:134
本文介绍了在Javascript中左边修剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有许多脚本用于修剪javascript中的字符串,但没有一个如何左边修剪字符串。

there are lots of scripts out there to trim a string in javascript, but none how to Left Trim String.

这是我用来修剪的:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

但我想稍微更改一下并创建一个名为leftTrim的新函数只删除前导空格。我的正则表达式非常有限,所以非常感谢任何帮助。

But I would like to change this a little and create a new function called leftTrim that only removes the leading space. My regex is pretty limited, so any help is much appreciated.

干杯

推荐答案

使用:

String.prototype.leftTrim = function() {
    return this.replace(/^\s+/,"");
}

在正则表达式中:


  • ^表示从字符串的开头

  • \s表示空白字符类

  • +表示一个或多个(贪婪)

所以....


  • ^ \s +表示从班级开始的一个或多个连续的空格字符

注意:正则表达式末尾的 g 标志是不必要的,因为锚点(^和$)明确定义了匹配的内容。不能有多个匹配。

Note: The g flag at the end of your regex is unnecessary as the anchors (^ and $) explicitly define what will match. There cannot be multiple matches.

参见 https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp ,了解有关javascript中正则表达式语法的详细信息

See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp for details on regex syntax in javascript

这篇关于在Javascript中左边修剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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