Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
868 views
in Technique[技术] by (71.8m points)

regex - Left Trim in Javascript

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

This is what I use to trim:

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

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.

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

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

In the regex the:

  • ^ means "from the beginning of the string"
  • s means whitespace character class
  • + means one-or more (greedy)

so....

  • ^s+ means "one or more consecutive whitespace characters from the beginning of the class"

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...