javascript - Insert before the last occurrence of a specific character in a string -
how insert before last occurrence of specific character?
if (statement) insert " again" string before last "<";
you can use lastindexof()
substring()
:
var str="hello planet earth, great planet."; var n=str.lastindexof("planet"); var str2 = str.substring(0,n)+" again "+str.substring(n); console.log(str2); // hello planet earth, great again planet.
as 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> <br> string <br> example."; var newstr = insertbeforelastoccurrence(str, "<", " again"); console.log(newstr); // <br> <br> string again<br> example.
or 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> <br> string <br> example."; console.log(str.insertbeforelastoccurrence("<", " again")); // output: <br> <br> string again<br> example. console.log(str.insertbeforelastoccurrence("w00t", " again")); // wont find // output: <br> <br> string <br> example.
Comments
Post a Comment