Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace last occurrence of a word in javascript?

for example:

var str="<br>hi<br>hi";

to replace the last(second) <br>,

to change into "<br>hihi"

I tried:

str.replace(/<br>(.*?)$/,\1);

but it's wrong. What's the right version?

like image 610
omg Avatar asked May 09 '09 09:05

omg


People also ask

How do you find the last occurrence of a character in a string in JavaScript?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

What is replace () in JavaScript?

The replace() method returns a new string with one, 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.

What is lastIndexOf in JavaScript?

lastIndexOf() The lastIndexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring.

How do I change the last character of a string in typescript?

replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); . The replace method will return a new string with the last character replaced by the provided replacement.


2 Answers

You can use the fact that quantifiers are greedy:

str.replace(/(.*)<br>/, "$1");

But the disadvantage is that it will cause backtracking.

Another solution would be to split up the string, put the last two elements together and then join the parts:

var parts = str.split("<br>");
if (parts.length > 1) {
    parts[parts.length - 2] += parts.pop();
}
str = parts.join("<br>");
like image 138
Gumbo Avatar answered Sep 30 '22 16:09

Gumbo


I think you want this:

str.replace(/^(.*)<br>(.*?)$/, '$1$2')

This greedily matches everything from the start to a <br>, then a <br>, then ungreedily matches everything to the end.

like image 35
Greg Avatar answered Sep 30 '22 16:09

Greg