js操作字串

來源:互聯網
上載者:User

標籤:rip   測試   位置   case   hello   調用   script   串連   rom   

js操作字串

from:https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434499203693072018f8878842a9b0011e3ff4e38b6b000
模板字串

要把多個字串串連起來,可以用+號串連:

var name = ‘小明‘;
var age = 20;
var message = ‘你好, ‘ + name + ‘, 你今年‘ + age + ‘歲了!‘;
alert(message);
如果有很多變數需要串連,用+號就比較麻煩。ES6新增了一種模板字串,表示方法和上面的多行字串一樣,但是它會自動替換字串中的變數:
var name = ‘小明‘;
var age = 20;
alert(`你好, ${name}, 你今年${age}歲了!`);


var name = ‘小明‘;
var age = 20;
var message = `你好, ${name}, 你今年${age}歲了!`;
alert(message);
練習:測試你的瀏覽器是否支援ES6模板字串,如果不支援,請把模板字串改為+串連的一般字元串:

// 如果瀏覽器支援模板字串,將會替換字串內部的變數:


var s = ‘Hello, world!‘;
s.length; // 13


var s = ‘Hello, world!‘;

s[0]; // ‘H‘
s[6]; // ‘ ‘
s[7]; // ‘w‘
s[12]; // ‘!‘
s[13]; // undefined 超出範圍的索引不會報錯,但一律返回undefined


JavaScript為字串提供了一些常用方法,注意,調用這些方法本身不會改變原有字串的內容,而是返回一個新字串:

toUpperCase

toUpperCase()把一個字串全部變為大寫:

var s = ‘Hello‘;
s.toUpperCase(); // 返回‘HELLO‘
toLowerCase

toLowerCase()把一個字串全部變為小寫:

var s = ‘Hello‘;
var lower = s.toLowerCase(); // 返回‘hello‘並賦值給變數lower
lower; // ‘hello‘
indexOf

indexOf()會搜尋指定字串出現的位置:

var s = ‘hello, world‘;
s.indexOf(‘world‘); // 返回7
s.indexOf(‘World‘); // 沒有找到指定的子串,返回-1
substring

substring()返回指定索引區間的子串:

var s = ‘hello, world‘
s.substring(0, 5); // 從索引0開始到5(不包括5),返回‘hello‘
s.substring(7); // 從索引7開始到結束,返回‘world‘

 

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.