可以使用字符串的 substring 方法来截取字符串:

const str = 'hello<span';
const result = str.substring(0, 5); // 截取从索引0开始到索引5(不包括5)的子字符串
console.log(result); // 输出 'hello'

另外,如果字符串中是固定的字符需要截取,也可以直接使用 split 方法来分割字符串:

const str = 'hello<span';
const result = str.split('<')[0]; // 使用 '<' 分割字符串,取第一个元素
console.log(result); // 输出 'hello'
JavaScript 字符串截取:截取 'hello' 的两种方法

原文地址: https://www.cveoy.top/t/topic/loGo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录