英文:
How to remove an array value from a string in Javascript
问题
"如何从字符串中删除数组值,示例:\n\njavascript\nvar String = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"\nvar array = [ "[1]", "[2]" ]\n\n---OUTPUT---\n\n"Hi my name is ftk: what is yours? [ and how are 2 5 you? Are you ok?"\n
\n基本上,我想要删除一个特定的数组,只有当它的值完全相同时才删除,如果有意义的话。\n\n我尝试过使用带有全局标志的.replace
,但我不能在那里使用数组,我只能输入一个特定的字符串,如下所示:\n\njavascript\nvar string2 = string.replace(/\\[1|\\]/g, '');\n
\n请参考上述示例,我无法同时删除2个单词,而且每次添加一个特定单词以删除都需要手动创建一个新的变量,因此使用数组会是最佳选择。\n\n提前感谢。"
英文:
Straight forward, How to remove an array value from a string, Example:
var String = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = [ "[1]", "[2]" ]
---OUTPUT---
"Hi my name is ftk: what is yours? [ and how are 2 5 you? Are you ok?"
Basically I want to remove a specific array and only when it's exactly the same word, If it makes sense.
I have tried .replace with global, But I couldn't use an array there, I can only input a specific string like:
var string2 = string.replace(/\[1|\]/g, '');
See above, I can't remove 2 words at the same time, And it would really suck to manually create a new var to it eachtime I add a specific word to remove, So an Array would be the best.
Thanks in Advance.
答案1
得分: 2
你只需遍历数组,逐个替换数组项即可:
let string = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
let array = ["[1]", "[2]"]
for (let i = 0; i < array.length; i++) {
string = string.replace(array[i], '');
}
console.log(string);
英文:
You can just loop through your array, replacing each array item as you go:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let string = "Hi my name is ftk: [2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
let array = [ "[1]", "[2]" ]
for (let i = 0; i < array.length; i++) {
string = string.replace(array[i], '');
}
console.log(string);
<!-- end snippet -->
答案2
得分: 1
你可以使用字符类来定义多个要移除的匹配项。然后在replace
的回调函数中,检查匹配项是否出现在array
中。
示例:
var string2 = string.replace(/\[[12]]/g, '');
var string = "[3] Hi my name is ftk: [2][2] what is yours? [ And how are 2 5 you? [1] Are you ok?";
var array = ["[1]", "[2]"];
var string2 = string.replace(
/\[[12]]/g,
m => array.includes(m) ? '' : m
);
console.log(string2);
英文:
You might use a character class to define multiple matches to remove. Then in the callback of replace, check if the match occurs in the array
.
\[[12]]
Example
var string2 = string.replace(/\[[12]]/g, '');
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var string = "[3] Hi my name is ftk: [2][2] what is yours? [ And how are 2 5 you? [1] Are you ok?"
var array = ["[1]", "[2]"];
var string2 = string.replace(
/\[[12]]/g,
m => array.includes(m) ? '' : m
);
console.log(string2);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论