How would I insert something before the last occurrence of a specific character?
if (statement) insert " again" into string before last "<";
To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string.
You can use lastIndexOf()
with substring()
:
var str="Hello planet earth, you are a great planet.";
var n=str.lastIndexOf("planet");
var str2 = str.substring(0,n)+" again "+str.substring(n);
console.log(str2); // Hello planet earth, you are a great again planet.
As a nice function:
function insertBeforeLastOccurrence(strToSearch, strToFind, strToInsert) {
var n = strToSearch.lastIndexOf(strToFind);
if (n < 0) return strToSearch;
return strToSearch.substring(0,n) + strToInsert + strToSearch.substring(n);
}
var str ="This <br> is another <br> string <br> example.";
var newStr = insertBeforeLastOccurrence(str, "<", " again");
console.log(newStr); // This <br> is another <br> string again<br> example.
Or as a String
method:
String.prototype.insertBeforeLastOccurrence = function(strToFind, strToInsert) {
var n = this.lastIndexOf(strToFind);
if (n < 0) return this.toString();
return this.substring(0,n) + strToInsert + this.substring(n);
}
var str ="This <br> is another <br> string <br> example.";
console.log(str.insertBeforeLastOccurrence("<", " again"));
// Output: This <br> is another <br> string again<br> example.
console.log(str.insertBeforeLastOccurrence("w00t", " again")); // wont find
// Output: This <br> is another <br> string <br> example.
You can get the last occurrence of a specified string using lastIndexOf(str)
, which is a member function of any String
or string
object. Then you can do something like this:
var idx = mystr.lastIndexOf("<");
if (idx > -1)
var outval = mystr.substr(0, idx) + " again" + mystr.substr(idx);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With