Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only text after last underscore in JavaScript string

Tags:

javascript

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'

like image 617
johowie Avatar asked Dec 12 '12 02:12

johowie


People also ask

How do you remove all underscore from a string in JavaScript?

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!

How do I replace a string underscore?

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.

How do you use underscore in JavaScript?

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.

Can JavaScript function include underscore?

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.


3 Answers

You can use a regular expression:

'Arthropoda_Arachnida_Zodariidae_Habronestes_hunti'.match(/[^_]*$/)[0];
like image 146
RobG Avatar answered Nov 03 '22 21:11

RobG


var index = str.lastIndexOf("_");
var result = str.substr(index+1);
like image 37
Teddy Avatar answered Nov 03 '22 20:11

Teddy


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).

like image 30
Peter Olson Avatar answered Nov 03 '22 21:11

Peter Olson