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

javascript - JavaScript的String strip()? [重复](String strip() for JavaScript? [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

Trim string in JavaScript?(在JavaScript中修剪字符串?) 25 answers(25个答案)

What's a clean and efficient JavaScript implementation to strip leading and trailing spaces from a string?(什么是从字符串中去除前导和尾随空格的干净高效的JavaScript实现?)

For example:(例如:) " dog" "dog " " dog " " dog " all get turned into(都变成了) "dog"   ask by rawrrrrrrrr translate from so

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

1 Reply

0 votes
by (71.8m points)

Use this:(用这个:)

if(typeof(String.prototype.trim) === "undefined") { String.prototype.trim = function() { return String(this).replace(/^s+|s+$/g, ''); }; } The trim function will now be available as a first-class function on your strings.(装饰函数现在将作为字符串的一等函数提供。) For example:(例如:) " dog".trim() === "dog" //true EDIT : Took JP's suggestion to combine the regex patterns into one.(编辑 :采纳了JP的建议,将正则表达式模式组合为一个。) Also added the global modifier per Christoph's suggestion.(还根据Christoph的建议添加了全局修饰符。) Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it.(重新创建修整功能之前,请听取Matthew Crumley的想法。) This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.(如果客户端使用的JavaScript版本较新,因此具有自己的本机修整功能,则可以这样做。)

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

...