如何在JavaScript中替换字符串的所有实例

news/2024/7/3 9:15:10

介绍 (Introduction)

Replacing text in strings is a common task in JavaScript. In this article you’ll look at using replace and regular expressions to replace text.

替换字符串中的文本是JavaScript中的常见任务。 在本文中,您将研究如何使用replace和正则表达式来替换文本。

更换单个实例 (Replacing A Single Instance)

Normally JavaScript’s String replace() function only replaces the first instance it finds in a string:

通常,JavaScript的String replace()函数仅替换它在字符串中找到的第一个实例:

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace('sentence', 'message');
console.log(newMessage); // this is the message to end all sentences

In this example, only the first instance of sentence was replaced.

在此示例中,仅替换了sentence的第一个实例。

替换多个实例 (Replacing Multiple Instances)

If you want JavaScript to replace all instances, you’ll have to use a regular expression using the /g operator:

如果您希望JavaScript替换所有实例,则必须使用/g运算符使用正则表达式:

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace(/sentence/g, 'message');
console.log(newMessage); // this is the message to end all messages

This time both instances are changed.

这次两个实例都被更改。

In addition to using the inline /g , you can use the constructor function of the RegExp object:

除了使用内联/g ,还可以使用RegExp对象的构造函数:

const myMessage = 'this is the sentence to end all sentences';
const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message');
console.log(newMessage); // this is the message to end all messages```

替换特殊字符 (Replacing Special Characters)

To replace special characters like -/\^$*+?.()|[]{}) we’ll need to use a backslash to escape them.

要替换特殊字符,例如-/\^$*+?.()|[]{})我们需要使用反斜杠将其转义。

Here’s an example. Given the string this\-is\-my\-url, let’s replace all the escaped dashes (\-) with an unescaped dash (-).

这是一个例子。 给定字符串this\-is\-my\-url ,我们将所有转义的破折号( \- )替换为未转义的破折号( - )。

You can do this with replace():

您可以使用replace()做到这一点:

const myUrl = 'this\-is\-my\-url';
const newUrl = myMessage.replace(/\\-/g, '-');
console.log(newUrl); // this-is-my-url

Alternatively, use new Regexp():

或者,使用new Regexp()

const myUrl = 'this\-is\-my\-url';
const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-');
console.log(newUrl); // this-is-my-url

In this second example, you don’t have to use a backslash to escape the backslash.

在第二个示例中,您不必使用反斜杠来转义反斜杠。

结论 (Conclusion)

In this article you saw how to replace single instances, multiple instances, and how to handle strings with special characters.

在本文中,您了解了如何替换单个实例,多个实例以及如何使用特殊字符处理字符串。

翻译自: https://www.digitalocean.com/community/tutorials/replace-all-instances-of-a-string-in-javascript


http://www.niftyadmin.cn/n/3649354.html

相关文章

[C#]I/O完成端口的实现

在VC中我几乎每一个Windows Service都是采用I/O完成端口。至于在C#中如何使用I/O完成端口,一直很少见人提及。William Kennedy的三篇文章《IOCP Thread Pooling in C#》,对实现这种机制很有帮助,唯一美中不足的是,它只能把int数值…

MyEclipse 10破解方法及下载地址

破解地址:http://blog.csdn.net/xexiyong/article/details/8273440 下载地址:http://xiazai.sogou.com/detail/34/16/-3776446113025264156.html?e1970

个人博客搭建教程——基于WordPress

WordPress是使用PHP语言开发的博客平台,是免费开源的。用户可以在支持PHP和MySQL数据库的服务器上架设属于自己的网站。也可以把WordPress当作一个内容管理系统(CMS)来使用。本教程采用NginxMySQLPHPWordPress搭建个人博客系统。 使用Wor…

python 代码生成器_如何为VS代码创建Python类生成器

python 代码生成器介绍 (Introduction) If you hate stubbing out Python classes, here’s how you can create an extension in Visual Studio Code to do it for you. In this article, you’ll see how to create that extension. We will use several techniques to do so…

[C#]如何将自定义的structure转换为byte[]?

如何将自定义的structure转换为byte[]?整理者:郑昀UltraPower示例如下:using System.Runtime.InteropServices;public static byte[] RawSerialize( object anything ){int rawsize Marshal.SizeOf( anything );IntPtr buffer Marshal.Allo…

在Node.js中使用服务器发送的事件来构建实时应用

The goal of this article is to present a complete solution for both the back-end and front-end to handle realtime information flowing from server to client. 本文的目的是为后端和前端提供一个完整的解决方案,以处理从服务器到客户端的实时信息流。 The…

鼠标点击页面出现富强自由等文字JS特效

在其他博客看到一款JS特效,感觉很不错,所有网上收集过来分享给大家。 效果参考本网站,添加点击特效,点击页面会显示: 富强, 民主, 文明, 和谐, 自由, 平等,公正 ,法治, 爱国, 敬业, 诚信, 友善 把以下代码添加到当前…

统一应用程序中所有Activity的栈管理

public class ActivityManager {//单例模式&#xff1a;饿汉式private ActivityManager(){}private static ActivityManager activityManager new ActivityManager();public static ActivityManager getInstance(){return activityManager;}//提供栈的对象private Stack<Ac…