js中多行字串拼接

來源:互聯網
上載者:User

標籤:alt   字串拼接   ref   技術   繁星   bsp   strong   多行   tin   

前言

我們會經常遇到這樣的情境,需要拼接多行字串,在字串中動態插入一些資料以達到業務的需求。但是js中並沒有標準的多行編輯的函數,於是聰明的程式員們便腦洞大開,書寫出許多有趣的方法。

12345 <div class="links"><a href="http://qianlongo.github.io/">謙龍的部落格</a><a href="http://aximario.github.io/">阿希的部落格</a><a href="http://lingyu.wang/">天鑲的部落格</a></div>

對於的dom結構如果要在js中拼接,你會用什麼組織方式呢?

1. 常規方式
1 var str = ‘<div class="links"><a href="http://qianlongo.github.io/">謙龍的部落格</a><a href="http://aximario.github.io/">阿希的部落格</a><a href="http://lingyu.wang/">天鑲的部落格</a></div>‘

看到上面那一坨的代碼,不知道您的心情是怎樣的,反正我是完全沒有心情看下去了,可讀性太差了,於是乎為了寫出可讀性強的代碼我們開始了下面的征程

2. 字串相加形式
12345 var str = ‘<div class="links">‘ +‘<a href="http://qianlongo.github.io/">謙龍的部落格</a>‘ +‘<a href="http://aximario.github.io/">阿希的部落格</a>‘ +‘<a href="http://lingyu.wang/">天鑲的部落格</a>‘ +‘</div>‘

這種也許是我們用的很多的一種方式,簡單靈活,可以直觀地看出dom結構,但是寫出來的代碼猶如滿天繁星一般,有些頭暈目眩

3. 反斜線
12345 ‘<div class="links">\<a href="http://qianlongo.github.io/">謙龍的部落格</a>\<a href="http://aximario.github.io/">阿希的部落格</a>\<a href="http://lingyu.wang/">天鑲的部落格</a>\</div>‘
4. 數組切割方式
1 [ ‘<div class="links">‘,‘<a href="http://qianlongo.github.io/">謙龍的部落格</a>‘,‘<a href="http://aximario.github.io/">阿希的部落格</a>‘,‘<a href="http://lingyu.wang/">天鑲的部落格</a>‘,‘</div>‘].join(‘\n‘);
5. es6 方式

es6的到來給我們帶來許多新的特性,其中有一部分是關於模板字串的,專門可以用來解決多行編輯的問題

12345 `<div class="links"><a href="http://qianlongo.github.io/">謙龍的部落格</a><a href="http://aximario.github.io/">阿希的部落格</a><a href="http://lingyu.wang/">天鑲的部落格</a></div>`

注意第一個和最後一個” ` “符號,整段代碼乾淨簡潔,太舒服了有木有

6. 黑魔法 function.toString()
1234567891011 function toSting(fn){return fn.toString().split(‘\n‘).slice(1,-1).join(‘\n‘) + ‘\n‘;} document.body.innerHTML = toString(function(){/*<div class="links"><a href="http://qianlongo.github.io/">謙龍的部落格</a><a href="http://aximario.github.io/">阿希的部落格</a><a href="http://lingyu.wang/">天鑲的部落格</a></div>*/})
總結

方法會有很多,適合自己的,適合解決實際問題的方法才是最好的方法。

js中多行字串拼接

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.