Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about javascript string's replace method

I know that I can pass a string as the second parameter to the JavaScript string object's replace method. In this case I can use $` and $' to reference the left/right part text of a successful match. Now my question is, If I pass a callback function as the second parameter, how can I get the same information? I want to use this infomation in the callback function. Great thanks.

like image 484
Just a learner Avatar asked Mar 01 '10 02:03

Just a learner


People also ask

How replace method works in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

Does string replace replacing all occurrences?

3.1 The difference between replaceAll() and replace()If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

Which function is used to replace string?

replace() The replace() method returns a new string with some or 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 called for each match. If pattern is a string, only the first occurrence will be replaced.


1 Answers

See Mozilla's documentation; you won't get that data for free.

The good news is, you will get the offset of the match as your second-to-last argument, and the total string as the last. So you can run your own substring functions.

var str = 'abc';
str = str.replace('b', function (match, offset, full) {
    var before = full.substr(0, offset),
        after = full.substr(offset + 1, full.length - offset);
    return 'foo'; // or, ya know, something actually using before and after
});
like image 140
Matchu Avatar answered Oct 25 '22 01:10

Matchu