網路上找到這個方法超好用的

原網址在此:http://yiding-he.iteye.com/blog/58180

在此筆記一下

一直以來都覺得 javascript 的字串有點麻煩

因為它不像C#一樣可以直接用如下的方式表示一個字串

string Str = @"

111

222

333

";

而原本 javascript 的字串如果要多行只能使用換行 \n

 

如下: 

var str = "111\n\

222\n\

333";

但是因為還要先去掉 \n 才是原內容,顯得很麻煩

本來直接一行的模式更難維護

var str = "111\n222\n333";

 

但是現在找到可以用註解的方式來做到多行字串的效果

第一種如下

======================================

function GetMultiLine(sStr) {

var s = sStr;

s = s.replace(/function/, '');

s = s.replace(/\(/, '');

s = s.replace(/\)/, '');

s = s.replace(/\{/, '');

s = s.replace(/\}/, '', -1);

s = s.replace(/\//, '');

s = s.replace(/\*/, '');

s = s.replace(/\//, '', -1);

s = s.replace(/\*/, '', -1);

return s;

}

var f = function () {

/*
the
quick
brown
fox
jumps
over
the lazy dog
*/

};

//使用方式

alert(GetMultiLine(new String(f)));

改寫之後如下

======================================

function getMultiLine(str) {

var lines = new String(str);

lines = lines.substring(lines.indexOf("/*") + 3, lines.lastIndexOf("*/"));

return lines;

}

var str = function () {

/*
111

222

333

*/

}

alert(getMultiLine(str));

將其加入至prototype 方便使用

Function.prototype.getMultiLine = function () {

var lines = new String(this);

lines = lines.substring(lines.indexOf("/*") + 3, lines.lastIndexOf("*/"));

return lines;

}

var str = function () {

/*

111

222

333

*/

}

alert(str.getMultiLine());

 

arrow
arrow
    全站熱搜

    小雕 發表在 痞客邦 留言(0) 人氣()