我需要用一个引号替换元素开头和结尾的两个引号。
我的代码是:
const regex = /['']/g;
let categories = [];
let categoryArray = data.categories.split(','); // ''modiles2'', ''Men''s Apparel'', ''Women''s Apparel'', ''Jeans'', ''Sneakers''
for (let value of Object.values(categoryArray)) {
categories.push(categoryArray[i].replace(regex, '\''));
}
}
return categories
// What should be 'modiles2','Men''s Apparel','Women''s Apparel','Jeans','Sneakers'
// What comes back ''modiles2'',''Men''s Apparel'',''Women''s Apparel'',''Jeans'',''Sneakers''
我的正则表达式只用一个引号替换了两个引号中的第一个。
我该如何解决这个问题?
最佳答案
字符类在方括号之间查找任何单个字符。具有重复字符的字符类(例如['']
)可以不进行此类重复。
"''modiles2'',''Men''s Apparel'',''Women''s Apparel'',''Jeans'',''Sneakers''"
.split(',')
.forEach(s => console.log( s.replace(/^''|''$/g, '\'') ))