網頁Web-Javascript-抓取字串中的文字-substr()、substring()

  • 18215
  • 0
  • Web
  • 2022-12-03

1.substr()

2.substring()

 

例如:

字串 = "HelloWorld"

0代表字串中第一個字元    /   H=第[0]個字元

1代表字串中第二個字元   /    e=第[1]個字元

-1代表字串中最後一個字元   / d=[-1]最後一個字元

-2代表倒數第二個字元     /   l=[-2]最後二個字元

1.抓取字串中的文字substr()

substr(第幾個字元開始,取幾個字元)

content = "ABC123QAZ789";

console.log(content.substr(2,3)) //C12 - 第2個字元開始取3個字元
console.log(content.substr(-4,2)) //Z7 - 倒數第4個字元開始取2個字元
console.log(content.substr(3)) //123QAZ789 -第3個字元開始抓取

https://codepen.io/yiruatstudio/pen/NWrJJro?editors=1111

2.抓取字串中的文字substring()

substring(第幾個字,到第幾個字);

content = "ABC123QAZ789";

console.log(content.substring(2)) //C123QAZ789 - 第二個字元開始取
console.log(content.substring(4,9)) //23QAZ - 取第4個字元到第9個字元
console.log(content.substring(10,13)) //89 - 取第10個字元到第13個字元

https://codepen.io/yiruatstudio/pen/bGeZZzX?editors=1111

 

 

 

Yiru@Studio - 關於我 - 意如