function String.prototype.Trim() { return this.replace(/(^/s*)|(/s*$)/g, ""); } // 去掉左右空格
function String.prototype.Ltrim() { return this.replace(/(^/s*)/g, ""); } // 去掉左空格
function String.prototype.Rtrim() { return this.replace(/(/s*$)/g, ""); } // 去掉右空格
eg.
- function getDDLValueForSelected(row) {
- // 設置選中行后,下拉菜單顯示選中的值
- if (G('ctl00_ddl01').disabled == "") { // 下拉菜單為啟用狀態
- if (row.cells(7).innerText != "") {
- for (var i = 0; i < G('ctl00_ddl01').options.length; i++) {
- if (textTrim(G('ctl00_ddl01').options[i].text) == textTrim(row.cells(1).innerText)) {
- G('ctl00_ddl01').selectedIndex = i;
- }
- }
- for (var j = 0; j < G('ctl00_ddl02').options.length; j++) {
- if (textTrim(G('ctl00_ddl02').options[j].text) == textTrim(row.cells(2).innerText)) {
- G('ctl00_ddlInterface').selectedIndex = j;
- }
- }
- }
- }
- }
- function textTrim(txt) {
- return txt.replace(/(^/s*)|(/s*$)/g, "");
- }
------------------------------
去除字符串左右兩端的空格,在vbscript里面可以輕松地使用 trim、ltrim 或 rtrim,但在js中卻沒有這3個內置方法,需要手工編寫。下面的實現方法是用到了正則表達式,效率不錯,並把這三個方法加入String對象的內置方法中去。
寫成類的方法格式如下:(str.trim();)
- <script language="javascript">
- String.prototype.trim=function(){
- return this.replace(/(^\s*)|(\s*$)/g, "");
- }
- String.prototype.ltrim=function(){
- return this.replace(/(^\s*)/g,"");
- }
- String.prototype.rtrim=function(){
- return this.replace(/(\s*$)/g,"");
- }
- </script>
寫成函數可以這樣:(trim(str))
- <script type="text/javascript">
- function trim(str){ //刪除左右兩端的空格
- return str.replace(/(^\s*)|(\s*$)/g, "");
- }
- function ltrim(str){ //刪除左邊的空格
- return str.replace(/(^\s*)/g,"");
- }
- function rtrim(str){ //刪除右邊的空格
- return str.replace(/(\s*$)/g,"");
- }
- </script>