JavaScript 字符串中删除首尾尖括号
可以使用正则表达式来检索字符串中的第一个<和最后一个>,然后使用字符串的replace方法将其删除。
let str = '<Hello> World <JavaScript>';
// 检索第一个<和最后一个>
let firstLessThanIndex = str.indexOf('<');
let lastGreaterThanIndex = str.lastIndexOf('>');
// 删除第一个<和最后一个>
let result = str.replace('<', '').replace('>', '');
console.log(result); // 输出:Hello World JavaScript
在上面的代码中,我们使用了字符串的indexOf方法来检索第一个<的位置,然后使用lastIndexOf方法来检索最后一个>的位置。然后,我们使用字符串的replace方法将第一个<替换为空字符串,再将最后一个>替换为空字符串,从而删除了它们。最终,输出的结果就是删除了第一个<和最后一个>的字符串。
原文地址: https://www.cveoy.top/t/topic/jGWz 著作权归作者所有。请勿转载和采集!