VUE3实现某字符串截取或删除指定位置的字符方法

VUE3实现某字符串截取或删除指定位置的字符方法

1. ‌substringslice截取法

通过字符串索引直接截取目标区间,适用于已知起始/结束位置的场景:

// 示例:删除第5个字符后的内容(索引从0开始)
const str = "Hello,Vue3!";
const result = str.substring(0, 5); // 输出 "Hello"‌:ml-citation{ref="3,4" data="citationList"}

// 或使用slice(支持负数索引)
const result2 = str.slice(0, -4); // 输出 "Hello,Vu"‌:ml-citation{ref="3,4" data="citationList"}

2. ‌lastIndexOf定位截取法

针对特定字符(如文件扩展名分隔符.或路径分隔符/)后的内容删除:

// 示例:删除最后一个`.`后的内容
const filename = "file.name.txt";
const index = filename.lastIndexOf(".");
const newName = filename.substring(0, index); // 输出 "file.name"‌:ml-citation{ref="5,6" data="citationList"}

3. ‌正则表达式匹配删除

灵活处理复杂规则(如删除特定模式后的内容):

// 示例:删除字符串中第一个`@`后的所有内容
const email = "user@example.com";
const cleaned = email.replace(/@.*/, ""); // 输出 "user"‌:ml-citation{ref="7" data="citationList"}

4. ‌split分割重组法

通过分隔符拆分字符串后重组:

// 示例:删除逗号分隔的第三个元素
const list = "A,B,C,D";
const arr = list.split(",");
arr.splice(2, 1); // 删除索引2的元素
const newList = arr.join(","); // 输出 "A,B,D"‌:ml-citation{ref="2,4" data="citationList"}

5、VUE3示例如下:

<template>
  <div>{{ processedStr }}</div>
</template>

<script setup>
import { ref, computed } from 'vue';

const originalStr = ref("Original-String-To-Process");

// 计算属性:删除第二个`-`后的内容
const processedStr = computed(() => {
  const index = originalStr.value.indexOf("-", originalStr.value.indexOf("-") + 1);
  return originalStr.value.substring(0, index); // 输出 "Original-String"‌:ml-citation{ref="3,4" data="citationList"}
});
</script>

6、方法对比与适用场景

方法适用场景优点缺点
substring/slice已知精确索引或固定位置高效直接需手动计算索引
lastIndexOf基于特定字符定位截断适用于动态分隔符场景仅支持单次匹配
正则表达式复杂模式或多条件匹配灵活性高正则语法学习成本
split重组结构化分隔内容(如CSV)便于批量操作元素内存占用较高(大字符串)

推荐场景‌:

  • 简单截取‌:优先使用substringslice
  • 动态分隔符‌:结合lastIndexOf定位‌
  • 复杂规则‌:正则表达式匹配‌