Заменить все вхождения строки javascript

Замена вхождения подстроки в строке JavaScript

Замена всех или n вхождений подстроки в заданной строке — довольно распространенная проблема манипуляций со строками и обработки текста в целом. JavaScript предлагает несколько способов сделать это довольно легко.

В этом руководстве мы рассмотрим несколько примеров того, как заменить вхождения подстроки в строке с помощью JavaScript.

Мы будем работать с этим предложением:

The grey-haired husky has one blue and one brown eye. 

Мы хотим заменить слово «blue» на «hazel» .

replace()

Самый простой способ сделать это — использовать встроенную функцию replace() . Она принимает регулярное выражение в качестве первого аргумента, а слова, которые мы заменяем старыми, в качестве второго аргумента. В качестве альтернативы он также принимает строку в качестве первого аргумента.

Поскольку строки в JavaScript неизменяемы, эта операция возвращает новую строку. Поэтому, если мы хотим сделать изменения постоянными, нам нужно будет присвоить результат новой строке при возврате.

Давайте посмотрим, как мы можем использовать функцию:

const regex = /blue/; let originalStr = 'The grey-haired husky has one blue and one brown eye.'; let newStr = originalStr.replace(regex, 'hazel'); console.log(originalStr); console.log(newStr); 

Здесь мы использовали литерал регулярного выражения вместо создания экземпляра RegExp . Это приводит к:

The grey-haired husky has one blue and one brown eye. The grey-haired husky has one hazel and one brown eye. 

В качестве альтернативы мы могли бы определить регулярное выражение как:

let regex = new RegExp('blue'); 

Результат был бы такой же. Разница между литералом регулярного выражения и объектом RegExp заключается в том, что литералы компилируются перед выполнением, а объект компилируется во время выполнения.

Первое более эффективно, если регулярное выражение остается постоянным, а второе обычно используется, если регулярное выражение может быть динамическим, например выражение, определенное пользователем.

Чтобы выполнить замену без учета регистра, вы можете передать флаг i в регулярное выражение:

const regex = /blue/i; let originalStr = 'The grey-haired husky has one Blue and one brown eye.'; let newStr = originalStr.replace(regex, 'hazel'); console.log(originalStr); console.log(newStr); 
The grey-haired husky has one Blue and one brown eye. The grey-haired husky has one hazel and one brown eye. 

Без флага i строка Blue не будет соответствовать регулярному выражению /blue/ .

Наконец, вы можете использовать строку вместо регулярного выражения:

let originalStr = 'The grey-haired husky has one blue and one brown eye.'; let newStr = originalStr.replace('blue', 'hazel'); console.log(originalStr); console.log(newStr); 
The grey-haired husky has one blue and one brown eye. The grey-haired husky has one hazel and one brown eye. 

Примечание: этот подход работает только для первого появления строки поиска. Чтобы заменить все вхождения, вы можете использовать функцию replaceAll() .

let originalStr = 'The grey-haired husky a blue left eye and a blue right eye.'; let newStr = originalStr.replace('blue', 'hazel'); 
The grey-haired husky has a blue left eye and a blue right eye. The grey-haired husky has a hazel left eye and a blue right eye. 

Обратите внимание, как заменяется только первое появление «blue», но не второе.

Обратите внимание, что на самом деле мы можем заменить все экземпляры строки при использовании подхода регулярных выражений и .replace() . Чтобы это произошло, мы можем использовать флаг регулярного выражения g , который означает «global». Это соответствует всем экземплярам в строке. Например:

const regex = /blue/g; let originalStr = 'The grey-haired husky a blue left eye and a blue right eye.'; let newStr = originalStr.replace(regex, 'hazel'); console.log(originalStr); console.log(newStr); 

replaceAll()

С августа 2020 года, как определено в спецификации ECMAScript 2021, мы можем использовать функцию replaceAll() для замены всех экземпляров строки.

Он принимает строку, которую мы ищем, и строку, которую мы хотели бы заменить:

let originalStr = 'The grey-haired husky has a blue left eye and a blue right eye.'; let newStr = originalStr.replaceAll('blue', 'hazel'); console.log(originalStr); console.log(newStr); 
The grey-haired husky has a blue left eye and a blue right eye. The grey-haired husky has a hazel left eye and a hazel right eye. 

Теперь все вхождения поискового слова заменены.

split() и join()

Если replaceAll() не поддерживается в режиме исполнения JavaScript, вы можете использовать старый добрый подход split() и join() :

let originalStr = 'The grey-haired husky has a blue left eye and a blue right eye.'; let newStr = originalStr.split('blue').join('hazel'); console.log(originalStr); console.log(newStr); 

Функция split() разбивает строку на массив подстрок по данной строке — ‘blue’ . После разделения у нас есть массив:

["The grey-haired husky has a ", " left eye and a ", " right eye."] 

Затем, когда мы используем join() , мы соединяем ее обратно к исходному предложению, при этом строка передается функции, вставленной в разрывы.

Теперь у нас остались все вхождения исходной строки, замененной новой:

The grey-haired husky has a blue left eye and a blue right eye. The grey-haired husky has a hazel left eye and a hazel right eye. 

Примечание. Хотя этот подход действительно работает, его не рекомендуется использовать, если доступен один из других ранее описанных методов. Причина этого в том, что цель этого подхода на первый взгляд не так очевидна, и поэтому код становится менее читабельным.

Вывод

В этой статье мы рассмотрели несколько примеров того, как можно заменить вхождения подстроки в строке с помощью JavaScript.

Источник

String.prototype.replaceAll()

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

Try it

Syntax

replaceAll(pattern, replacement) 

Parameters

Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn’t have the Symbol.replace method will be coerced to a string.

If pattern is a regex, then it must have the global ( g ) flag set, or a TypeError is thrown.

Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace() .

Return value

A new string, with all matches of a pattern replaced by a replacement.

Exceptions

Thrown if the pattern is a regex that does not have the global ( g ) flag set (its flags property does not contain «g» ).

Description

This method does not mutate the string value it’s called on. It returns a new string.

Unlike replace() , this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.

function unsafeRedactName(text, name)  return text.replace(new RegExp(name, "g"), "[REDACTED]"); > function safeRedactName(text, name)  return text.replaceAll(name, "[REDACTED]"); > const report = "A hacker called ha.*er used special characters in their name to breach the system."; console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system." console.log(safeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system." 

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll() . In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).

If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.

For more information about how regex properties (especially the sticky flag) interact with replaceAll() , see RegExp.prototype[@@replace]() .

Источник

Читайте также:  Django rest framework html template
Оцените статью