js字符串去除指定字符

CaixK
  • 341

我这样去为什么去不掉'[',']'

let str1 = JSON.stringify(this.checkboxGroupFrom)//[1,2,3,4,6,7]
typeof(str1)
str1.replace("[","")
str1.replace("]","")
console.log(str1)
回复
阅读 5.6k
8 个回答

上面这些哥们都没回答到重点,replace 不会改变原来的字符串,而是会产生一个新的字符串。

mdn 文档这样定义的:

clipboard.png

参考链接:https://developer.mozilla.org...

况且你要拿到数组里面的每个分量根本不用这样做啊,直接用 join 方法:

clipboard.png

参考链接:https://developer.mozilla.org...

this.checkboxGroupFrom = [1,2,3,4,6,7]
str1 = this.checkboxGroupFrom.join(',') //1,2,3,4,5,6,7
str2 = this.checkboxGroupFrom.join('') //1234567

let str1 = JSON.stringify(this.checkboxGroupFrom)//[1,2,3,4,6,7]
typeof(str1)
str1 = str1.replace("[","")
str1 = str1.replace("]","")
console.log(str1)

// 缺少赋值

这是typescript吗?

let str1 = JSON.stringify(this.checkboxGroupFrom)//[1,2,3,4,6,7]
typeof(str1)
let st2=str1.replace("[","")
let st3=st2.replace("]","")
console.log(st3);

不过建议你用正则表达式 str1.replace(/[\[\]]/g,'');

缺少赋值 str1=str1.replace(']','')个人觉得用3楼方法的更好

let str1 = JSON.stringify(this.checkboxGroupFrom);
let str = /^\[(.*?)\]$/.exec(str1)[1];
console.log(str);

replace 会返回一个新的字符串而不会改变原有字符串,所以你那样写肯定就不会得到想要的结果。

this.checkboxGroupFrom = [1,2,3,4,5,6,7];
        let str1 = JSON.stringify(this.checkboxGroupFrom);//[1,2,3,4,6,7]
        console.log(typeof(str1));
        let str = str1.substr(1);
        let strNew = str.substr(0,str.length-1);
        console.log(strNew);
this.checkboxGroupFrom = [1,2,3,4,5,6,7];
        let str1 = JSON.stringify(this.checkboxGroupFrom);//[1,2,3,4,6,7]
        console.log(typeof(str1));
        let str = str1.replace("[","");
        let strNew = str.replace("]","");
        console.log(strNew);

试试这两个

你知道吗?

宣传栏