Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
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.
Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);
Using replace() function. In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.
strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c'; console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
This will replace it with the contents of the variable replacement
:
var str = 'a_b_c', replacement = '!'; console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
No need for jQuery nor regex assuming the character you want to replace exists in the string
Replace last char in a string
str = str.substring(0,str.length-2)+otherchar
Replace last underscore in a string
var pos = str.lastIndexOf('_'); str = str.substring(0,pos) + otherchar + str.substring(pos+1)
or use one of the regular expressions from the other answers
var str1 = "Replace the full stop with a questionmark." var str2 = "Replace last _ with another char other than the underscore _ near the end" // Replace last char in a string console.log( str1.substring(0,str1.length-2)+"?" ) // alternative syntax console.log( str1.slice(0,-1)+"?" ) // Replace last underscore in a string var pos = str2.lastIndexOf('_'), otherchar = "|"; console.log( str2.substring(0,pos) + otherchar + str2.substring(pos+1) ) // alternative syntax console.log( str2.slice(0,pos) + otherchar + str2.slice(pos+1) )
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