gpt4 book ai didi

javascript - 2 个字符串替换 javascript

转载 作者:行者123 更新时间:2023-11-30 07:26:06 25 4
gpt4 key购买 nike

我是初学者,我该如何组合它们:

var mystring = "my.email@computer.com";
document.write(mystring.replace(/@/, "&&"));

打印 my.email&&computer.com

var mystring = "my.email@computer.com";
document.write(mystring.replace(/\./, "##"));

打印my##email@computer.com

我有两个问题:如何在 @ 之后将此正则表达式 (mystring.replace(/./, "##") 更改为 ##以及如何将这两行合并为一行,最终阅读内容为:my.email&&computer##com

最佳答案

输入:my.first.last.email@example.computer.com

结果:my.first.last.email&&example##computer##com

解决方案一:

var mystring = "my.first.last.email@example.computer.com";
//replace '.' after '@' with '##', then replace '@' with '&&'.
var result = mystring.replace(/(?!.*@)\./g, "##").replace(/@/, "&&");
document.write(result);

解决方案 2(可配置):

var mystring = "my.email@computer.com";

var replacements = {
'@' : '&&',
'.' : '##'
};

var str = "my.first.last.email@example.computer.com";

//match latter part of the string
var result = str.replace(/@\w+(\.\w+)+/g, function(at_and_after) {
//replace all '.' and '@' in that part.
return at_and_after.replace(/@|\./g, function(m) { return replacements[m]});
});
document.write(result); //console.log(result) or alert(result) is a better way for demo

关于javascript - 2 个字符串替换 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14743204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com