點燈坊

失くすものさえない今が強くなるチャンスよ

Substring to Specific Character

Sam Xiao's Avatar 2022-12-16

If we want to substring to a specific character, we can’t just use substring() to get the result.

Version

ECMAScript 2015

substring()

let s = 'B8棟'

let end = s.indexOf('棟')
s.substring(0, end) // ? B8
  • indexOf():get the index of the specific character
  • substring():substring the result without the specific character

Conclusion

  • Since both parameters of substring() are index, we can use indexOf() to get the index of the specific character first

Reference

MDN, String.prototype.indexOf()
MDN, String.prototype.substring()