Cross-Browser Regular Expression Library for Javascript to Replace Function Used

Is there a library to replace using functions as an argument

when i call this function

"foo[10]bar[20]baz".replacef(/\[([0-9]*)\]/g, function(a) {
    return '[' + (ParseInt(a)*10) + ']';
});

he must return

"foo[20]bar[30]baz";

and when I call with this

"foo[10;5]bar[15;5]baz".replacef(/\[([0-9]*);([0-9]*)\]/g, function(a, b) {
    return '_' + (ParseInt(a)+ParseInt(b)) + '_';
});

he must return

"foo_15_bar_20_baz"

Is there an existing Cross-Browser library that has the same or similar function in JavaScript?

+3
source share
2 answers

How the "replace ()" function works. If the second parameter is a function, it passed a list of arguments that are almost the same as the array returned by the RegExp "exec ()" function. The function returns what it wants the matched region to be replaced.

. - (, ). .

:

var s = "hello world".replace(/(\w+)\s*(\w+)/, function(wholeMatch, firstWord, secondWord) {
  return "first: " + firstWord + " second: " + secondWord;
});
alert(s); // "first: hello second: world"
+5

, - javascript:

"foo[10]bar[20]baz".replace(/\[([0-9]+)\]/g, function() {
  return '[' + (parseInt(arguments[1])*10) + ']';
});

afaik ( , parseInt p), , 0 - , 1 .. - .

+2

Source: https://habr.com/ru/post/1794753/


All Articles