如何将替换应用于字符串的每个元素?在Javascript中

时间:2018-06-13 19:25:29

标签: javascript string

我想知道如何用另一个字符串替换字符串中的每个元素。

使用替换正确,但如果我发送某个特定字符的完整行,只有第一个替换我。

示例:

let e = "________1", y;

y = e.replace("_","0");

console.log(y);

2 个答案:

答案 0 :(得分:1)

使用正则表达式和全局(g)标志:



const pattern = /_/g;
const e = '________1';
const y = e.replace(pattern, '0');

console.log(y);




答案 1 :(得分:1)

您需要在“find”参数中使用 regular expression ,以便指定“Global Find& Replace”标记(g)。 (向下滚动到我所包含的链接中的“使用标记进行高级搜索”部分,以阅读g。)

let e = "________1", y;

y = e.replace(/_/g,"0"); // Regular expression is delimited by / and /

console.log(y);