If I have a string like so:
var str = 'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti';
How can I get just the last part of the string after the last underscore?
And in the case there are no underscores just return the original string.
In this case I want just 'hunti'
To remove the underscores from a string, call the replaceAll() method on the string, passing it an underscore as the first parameter, and an empty string as the second, e.g. replaceAll('_', '') . The replaceAll method will return a new string, where all underscores are removed. Copied!
Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.
Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.
Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private.
You can use a regular expression:
'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti'.match(/[^_]*$/)[0];
var index = str.lastIndexOf("_");
var result = str.substr(index+1);
It's very simple. Split the string by the underscore, and take the last element.
var last = str.split("_").pop();
This will even work when the string does not contain any underscores (it returns the original string, as desired).
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