Javascript replace all callback

TIL: JavaScript replace() command with callback

Of course, this is not new, it’s already here centuries ago in the document https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace, but I never have to do any replacement complicated enough to use it, so I pay no attention to it until I read a pull request from a teammate today. The replace() command in JavaScript has a callback that provided you with some more information such as the matched content, the index, and the original string. What you return in that callback will be replaced to the matched content. This allows you to have a more complicated replacement, for example: you want to replace just the second occurrence of the letter «a» in «abcabc» to the letter «$» . How would you write a regex for that? What if we change the requirement
to any nth occurrence? Even if you find a regex solution, is it
elegant enough to not making any other developer vomit when they had to maintain your code? Using replace() with a callback, we can just write:

"abcabc".replace(/a/g, (matched, index, original) => < if (index !== 0) < return "$"; >else < return matched; >>); 

That’s it, stop writing complicated regexes, start using replace()
with callbacks, it makes things easier. You and your teammates, all have a life to live, and sanity to save.

Читайте также:  Task distribution in java

Top comments (5)

. former musician, voice actor, martial artist, started coding 38 years ago and turned front-end developer 25+ years ago.

Yes, replace with a callback is pretty powerful. However, keep in mind that regular expressions are meant to solve regular problems and will easily fail on irregular tasks.

Also, your understanding of the syntax is slightly imcomplete, it actually is:

String.prototype.replace(regExp, callback( fullMatch: string, . capturedMatches: string[], positionOfFullMatchInString: number, inputString: string )) 

Captured matches are what you get from using parentheses in your RegExp. The position in the string like all string functions in JS counts UTF-16/-32 chars as multiple characters. Unlike a lot of other methods, the callback is not run in the scope of the object it is called on, so this will default to the global scope unless manually bound.

7 likes Like Comment button

Источник

Коллбэк в методе replace в регулярках JavaScript

Метод replace вторым параметром может принимать не только строку, но и функцию-коллбэк, которая применится для каждого найденного совпадения. Каждая подстрока, которую нашла регулярка, заменится на то, что вернет эта функция именно для этой подстроки.

В эту функцию можно передавать параметры: в первый параметр положится найденная строка, во второй параметр — первый карман, в третий параметр — второй карман и так далее — можно делать сколько параметров, сколько карманов в регулярном выражении.

В предпоследний параметр положится позиция найденного совпадения, а в последний — вся строка, по которой делается поиск.

Как это все работает — разберем на практических примерах.

Пример

Пусть дана строка с числами:

Давайте заменим эти числа на их квадраты. Для начала давайте просто выведем наши числа по очереди в консоль в функции-коллбэке:

Наш код выведет сначала ‘2’ , потом ‘3’ , ‘4’ и ‘5’ . То есть в переменную match последовательно попадают те строки, которые нашла регулярка.

Давайте решим задачу до конца — будем возводить match в квадрат и возвращать его с помощью return . Получится, что для найденной двойки вернется 4 и двойка заменится на эту четверку, для найденной тройки вернется 9 и тройка заменится на эту девятку — и так далее:

Пример

Пусть теперь в строке даны конструкции вида ‘2+3=’ :

Давайте сделаем так, чтобы после равно вставились суммы соответствующих чисел. То есть наша строка должна превратиться в следующую:

Для решения задачи давайте опять поэкспериментируем — разложим первое и второе слагаемые по отдельным карманам:

А теперь окончательно решим задачу: для каждой найденной подстроки просуммируем первый и второй карманы, возьмем нулевой карман (найденную строку, например ‘2+3=’ ), добавим к нему результат и вернем все это через return :

Практические задачи

Найдите числа, стоящие в скобках и увеличьте их в два раза. То есть из нашей строки должна получится следующая:

Найдите все числа и переверните их цифры в обратном порядке. То есть из нашей строки должна получится следующая:

Найдите все даты и преобразуйте их в другой формат так, чтобы получилась следующая строка:

Источник

How to Pass Callback Functions to String.replace() in JavaScript

Dillion Megida

Dillion Megida

How to Pass Callback Functions to String.replace() in JavaScript

Did you know that the string .replace() method accepts a callback function? I just discovered it today and thought I’d share.

What do you need this function for? Why does it exist? I’ll answer all these questions as you go through this article.

The replace() Method

The replace() string method replaces text characters in a string. It takes two arguments: the string to be replaced, and the value it should be replaced with.

With this method, you can replace string characters (like «hello») or characters that match a RegEx pattern (like /hi/ ).

Here’s the syntax of this method:

String.replace(string/pattern, replacer) 

Here are some examples showing how to use this method:

const sentence = "Hi my name is Dillion" const replaced1 = sentence.replace("Dillion", "JavaScript") console.log(replaced1) // "Hi my name is JavaScript" const replaced2 = sentence.replace(/\s/g, "-") console.log(replaced2) // "Hi-my-name-is-Dillion" 

But, the replacer argument can also be a function.

Why would you need to use a function as the replacer method?

The reason is that sometimes, you want to do something with those characters that match the specified pattern.

String.replace(/pattern/, function(matched)< // do something with matched and return // the replace value >) 

If you’re using a literal string pattern like «Dillion», you do not need the callback function because you already know that it’s only «Dillion» you’re matching through the sentence.

But with RegEx patterns, it can match multiple things. Here’s an example:

const sentence = "I am a good guy and you too" const replaced = sentence.replace(/g\S*/g, "😂") console.log(replaced) // I am a 😂 😂 and you too 

The regex pattern matches all words that start with «g» and two words match; «good» and «guy». In this case, if we want to do something with the matched value, we would need the callback.

const sentence = "I am a good guy and you too" const replaced = sentence.replace(/g\S*/g, function(matched)< console.log("matched", matched) return "😂" >) console.log(replaced) // matched good // matched guy // I am a 😂 😂 and you too 

What are the examples of things we can do with matched values? There are so many scenarios, but I’ll use the one use case that led me to discover this.

How to find and replace URLs in a text with RegEx

On platforms like WhatsApp and Twitter, you’ll discover that when you make a post or message with a link, the link is colored differently from other text and behaves like a link. Then when it’s clicked, it navigates the user to a separate page.

How do they achieve this? The idea is to replace the links in the text with an element that has some styles to it and also works as a link.

Here’s how I did this with JavaScript:

const text = "My website is https://dillionmegida.com and I write on http://freecodecamp.org/" const regex = /https?:\/\/\S*/gi const modifiedText = text.replace(regex, (url) => < return `">$ ` >) console.log(modifiedText) // My website is https://dillionmegida.com and I write on http://freecodecamp.org/ 

The regex matches patterns with «https://. » (with the s optional). Using the callback, I can get the url that matches the regex and use it to create an anchor tag string with a «text—link» class.

With this returned string, I can inject it into the DOM. In my case, I was using React, so I used dangerouslySetInnerHTML to inject it into a paragraph. I can specify a color for the «text—link» class in my stylesheet.

Conclusion

We learn new things every day, and I hope you’ve learned something in JavaScript today – the callback function in String.replace() .

Also, in this article, I showed a good use case for taking advantage of this function.

Kindly share this if you find it helpful.

Источник

JavaScript String replaceAll

Summary: in this tutorial, you’ll learn about the String replaceAll() method that replaces all occurrences of a substring with a new string.

Introduction to the JavaScript string replaceAll() method

The String replace() method allows you to replace the first occurrence of a substring in a string with a new one.

To replace all the occurrences of a substring with a new one, you can call the replace() method repeatedly or use a regular expression with a global flag ( g ).

ES2021 introduced the String replaceAll() method that returns a new string with all matches of a pattern replaced by a replacement:

String.prototype.replaceAll(pattern, replacement)Code language: CSS (css)

The pattern can be a string or a regular expression. When the pattern is a regular expression, it needs to include the global flag ( g ); otherwise, the replaceAll() will throw an exception.

The assumption is that you made a mistake and should have used the replace() method to replace the first occurrence that matches the pattern only.

The replacement argument can be a string or a callback function that will be invoked for each match.

When the replacement is a callback function, it has the following form:

replacement(match, offset, str)

The replacement callback has the following arguments:

  • match is the matched substring.
  • offset is offset of the matched substring within the original string. For example, if the original string is ‘Hello’ and the matched substring is ‘ll’ , then the offset will be 2.
  • str is the original string.

Like the replace() method, the replaceAll() method doesn’t change the original string. It returns the new completely new string with the pattern replaced by the replacement.

JavaScript String replaceAll() examples

Let’s take some examples of using the JavaScript String replaceAll() method.

1) Simple JavaScriptString replaceAll() example

The following example uses the String replaceAll() method to replace the string JS with the string JavaScript in the string ‘ JS will, JS will, JS will rock you’ :

let str = 'JS will, JS will, JS will rock you.'; let newStr = str.replaceAll('JS','JavaScript'); console.log(newStr);Code language: JavaScript (javascript)
JavaScript will, JavaScript will, JavaScript will rock you. 

2) JavaScript String replaceAll() with a callback function example

The following example uses the String replaceAll() method to search for a substring by a regular expression. It replaces each match with a specific replacement determined by a callback function:

let str = 'JS will, Js will, js will rock you.'; let pattern = /js/gi; str.replaceAll(pattern, function(match, offset, str) < if(match === 'JS') return 'JavaScript'; if(match === 'Js') return 'Javascript'; if(match === 'js') return 'javascript'; return ''; >); console.log(newStr);Code language: JavaScript (javascript)
JavaScript will, Javascript will, javascript will rock you. 

The regular expression /js/gi matches any string that contains the substring JS case-insensitively i.e, JS , Js , or js .

The replaceAll() method replaces the substring JS , Js , and js with the returned value of the replacement callback.

Summary

  • Use the JavaScript string replaceAll() method to replace all occurrences of a substring with a new one in a string.

Источник

Оцените статью