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
930 views
in Technique[技术] by (71.8m points)

regex - trim in javascript ? what this code is doing?

I was looking for a trim function in JavaScript which doesn't exist and some code on Googling suggests that use:

function trimStr(str) {
  return str.replace(/^s+|s+$/g, '');
}

I want to know how str.replace(/^s+|s+$/g, '') works. I understand that this is some form of regular expression but dont know what it is doing.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

/^s+|s+$/g searches for whitespace from either the beginning or the end of the string. The expression can be split into two parts, ^s+ and s+$ which are separated by | (OR). The first part starts from the beginning of the string (^) and includes as many whitespace characters it can (s+). The second part does the same but in reverse and for the end using the dollar sign ($).

In plain english, the regular expression would go like this:

Find as many whitespace characters from the beginning of the string as possible or as many whitespace characters from the end as possible.

Note that s matches spaces, tabs and line breaks.

The /g part at the end enables global searching, which allows multiple replacements (eg. not just the beginning, but the end of the string also).


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

...