JavaScript中去掉字符串中的斜杠'/'的常用方法
文章标签:
去除html
- 使用正则表达式,使用 replace() 函数将所有 / 替换为空字符串:
let str = "this/is/a/string";
str = str.replace(/\//g, "");
console.log(str); //输出: "thisisastring"
- 使用 split() 函数将字符串按照 / 分割成数组,然后使用 join() 函数将数组合并为一个字符串:
let str = "this/is/a/string";
str = str.split("/").join("");
console.log(str); //输出: "thisisastring"
- 使用 replaceAll() 函数将所有 / 替换为空字符串(这是 ES2021 新增的函数):
let str = "this/is/a/string";
str = str.replaceAll("/", "");
console.log(str); //输出: "thisisastring"
- 使用 replace() 函数将第一个 / 替换为空字符串,然后重复调用直到替换完所有 /:
let str = "this/is/a/string";
while (str.indexOf("/") !== -1) {
str = str.replace("/", "");
}
console.log(str); //输出: "thisisastring"
注意:以上方法都会修改原始字符串,如果需要保留原始字符串,需要将结果赋值给一个新的变量。