迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中替换字符串

作者:迹忆客 最近更新:2023/03/09 浏览次数:

替换字符串的方法有多种,包括 replace() 方法、regular expressionsplit()join() 一起,以及 PHP str_replace() 方法的副本。

本篇文章讨论了如何在 JavaScript 中复制 PHP str_replace() 函数,以及一起使用 split()join() 方法来替换 JavaScript 中的字符串。你可以在这里找到更多关于 split()join() 的信息。

split() 方法根据 separator 拆分原始字符串。它在不更改原始字符串的情况下输出新的子字符串数组。

join() 函数根据 separator 连接所有数组元素。它返回一个新字符串而不更新原始字符串。

JavaScript 代码:

let message = "This is a dummy text that we want to replace using replace function.";
let new_message = message.split("want").join("do not want");
console.log(new_message);

输出:

"This is a dummy text that we do not want to replace using replace function."

split() 函数在找到 want 的位置拆分 message 并返回两个子字符串 "This is a dummy text that we "" to replace using replace function."。请记住,它在破坏字符串时不会删除空格。

join() 方法将这两个子字符串与 do not want 连接起来,并输出为 "This is a dummy text, we don't want to replace using replace function."

下面的代码演示了每个函数如何操作并提供更详细的输出。

JavaScript 代码:

let message = "This is a dummy text that we want to replace using replace function.";
let split_message = message.split("want")
let new_message = split_message.join("do not want");
console.log(message);
console.log(split_message);
console.log(new_message);

输出:

"This is a dummy text that we want to replace using replace function."
["This is a dummy text that we ", " to replace using replace function."]
"This is a dummy text that we do not want to replace using replace function."

JavaScript 代码:

function str_replace($searchString, $replaceString, $message) {
  	// We create regext to find the occurrences
 	var regex;

 	// If the $searchString is a string
 	if ( typeof($searchString) == "string" ) {
		// Escape all the characters used by regex
 		$searchString = $searchString.replace(/[.?*+^$[\]\\(){}|-]/g, "\\");
 		regex = new RegExp("(" + $searchString + ")", "g");
    } else {
		 // Escape all the characters used by regex
 		$searchString = $searchString.map(function(i) {
 			return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\");
        });
	    regex = new RegExp("(" + $searchString.join("|") + ")", "g");
    }
 	// we create the replacement
 	var replacement;

 	// If the $searchString is a string
 	if ( typeof($replaceString) == "string" ) {
 		replacement = $replaceString;
    } else {
 		// If the $searchString is a string and the $replaceString an array
 		if ( typeof($searchString) == "string" ) {
 			replacement = $replaceString[0];
        } else {
 			// If the $searchString and $replaceString are arrays
 			replacement = function (i) {
 				return $replaceString[ $searchString.indexOf(i) ];
            }
        }
    }
	return $message.replace(regex, replacement);
}
let message = "This is a dummy text that we want to replace using replace function.";
console.log(str_replace("want", "do not want", message));

输出:

"This is a dummy text that we do not want to replace using replace function."

对于上面的示例,str_replace() 方法采用三个参数:$searchString$replaceString$message

它首先创建 regex (/[want]/g),考虑 $searchString 是否属于 string 类型而不是。然后,我们考虑各种情况创建替换

例如,如果 $searchString 是否是 string。如果不是,请检查 $searchString 是否是 string$replaceString 是否是数组或 $searchString$replaceString 是否都是数组。

最后,我们在 replace() 方法中使用此 regexreplacement 来获得所需的输出。我们可以优化上面给出的长代码以获得准确的输出。

JavaScript 代码:

function str_replace($search, $replace, $message) {
  return $message.replace(new RegExp("(" + (typeof($search) == "string" ?
      $search.replace(/[.?*+^$[\]\\(){}|-]/g, "\\") :
      $search.map(function(i) {
        return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\")
      }).join("|")) + ")", "g"), typeof($replace) == "string" ?
    $replace : typeof($search) == "string" ? $replace[0] : function(i) {
      return $replace[$search.indexOf(i)]
    });
}
let message = "This is a dummy text that we want to replace using replace function.";
console.log(str_replace("want", "do not want", message));

输出:

"This is a dummy text that we do not want to replace using replace function."

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便