在 JavaScript 中替换字符串

Mehvish Ashiq 2023年10月12日
  1. 在 JavaScript 中使用 split()join() 方法替换字符串
  2. 在 JavaScript 中复制 PHP str_replace() 函数来替换字符串
在 JavaScript 中替换字符串

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

本教程讨论了如何在 JavaScript 中复制 PHP str_replace() 函数,以及一起使用 split()join() 方法来替换 JavaScript 中的字符串。

在 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 中复制 PHP str_replace() 函数来替换字符串

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."
作者: Mehvish Ashiq
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

相关文章 - JavaScript String