Javascript 替换打字稿中字符串中的所有字符实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43310947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:49:54  来源:igfitidea点击:

Replace all instances of character in string in typescript?

javascriptstringtypescriptreplaceglobal

提问by Rebecca

I'm trying to replace all full stops in an email with an x character - for example "[email protected]" would become "myxemail@emailxcom". Email is set to a string.
My problem is it's not replacing just full stops, it's replacing every character, so I just get a string of x's.
I can get it working with just one full stop, so I'm assuming I'm wrong on the global instance part. Here's my code:

我试图用 x 字符替换电子邮件中的所有句号 - 例如“[email protected]”将变成“myxemail@emailxcom”。电子邮件设置为字符串。
我的问题是它不只是替换句号,而是替换每个字符,所以我只得到一串 x。
我只需一个句号就可以让它工作,所以我假设我在全局实例部分错了。这是我的代码:

let re = ".";
let new = email.replace(/re/gi, "x");

I've also tried

我也试过

re = /./gi;
new = email.replace(re, "x");

If anyone can shed any light I'd really appreciate it, I've been stuck on this for so long and can't seem to figure out where I'm going wrong.

如果有人能提供任何线索,我将不胜感激,我已经坚持了这么久,似乎无法弄清楚我哪里出错了。

** Edit: Whoops, my new variable was actually called newemail, keyword new wasn't causing the issue!

** 编辑:哎呀,我的新变量实际上被称为 newemail,关键字 new 没有引起问题!

回答by gyre

Your second example is the closest. The first problem is your variable name, new, which happens to be one of JavaScript's reserved keywords(and is instead used to construct objects, like new RegExpor new Set). This means that your program will throw a Syntax Error.

你的第二个例子是最接近的。第一个问题是您的变量名,new,它恰好是 JavaScript 的保留关键字之一(而是用于构造对象,例如new RegExpnew Set)。这意味着您的程序将抛出语法错误。

Also, since the dot (.) is a special character inside regex grammar, you should escape it as \.. Otherwise you would end up with result == "xxxxxxxxxxxxxxxxxx", which is undesirable.

此外,由于点 ( .) 是正则表达式语法中的特殊字符,您应该将其转义为\.. 否则你最终会得到result == "xxxxxxxxxxxxxxxxxx",这是不可取的。

let email = "[email protected]"

let re = /\./gi;
let result = email.replace(re, "x");

console.log(result)

回答by Ajay Gupta

You can try split()and join()method that was work for me. (For normal string text) It was short and simple to implement and understand. Below is an example.

您可以尝试split()join()方法,这是为我工作。(对于普通的字符串文本)它的实现和理解都很简短。下面是一个例子。

let email = "[email protected]";
email.split('.').join('x');

So, it will replace all your .with x. So, after the above example, emailvariable become myxemail@gmailxcom

因此,它将.x. 所以,经过上面的例子,email变量变成myxemail@gmailxcom