乐闻世界logo
搜索文章和话题

How to replace all dots in a string using JavaScript

1个答案

1

In JavaScript, if you want to replace all occurrences of dots (.), you can use the replace method with a regular expression. Since the dot (.) is a special character in regular expressions representing any single character, you need to escape it with a backslash () to make it a literal dot. Next, you must add the global search flag (g) to replace all dots, not just the first one.

Here is a specific example:

javascript
// Assume we have the following string let myString = "Hello.JavaScript.World."; // Use the replace method with a regular expression to replace all dots let replacedString = myString.replace(/\\./g, "-"); console.log(replacedString);

In this example, all dots (.) are replaced with hyphens (-). The output will be:

shell
Hello-JavaScript-World-

This method is highly effective and suitable for globally replacing any special characters or string patterns.

2024年6月29日 12:07 回复

你的答案