Skip to content Skip to sidebar Skip to footer

Getting All Characters After The Last '-' In A String

I am working within some very strict pack-end limitations and have a client that is unrelenting in his request so I'm forced to do something in .js that I'd rather not do. Anyway,

Solution 1:

No need for jQuery for the actual string manipulation - a little clunky, but easy to understand:

text = 'Something -that - has- dashes - World';parts = text.split('-');loc = parts.pop();new_text = parts.join('-');

So,

loc == ' World';new_text == 'Something -that - has- dashes ';

Whitespace can be trimmed or ignored (as it often doesn't matter inside HTML).

Solution 2:

First split the stirng on '-' which will give you an array of strings between the dashes. Then use it as a stack and pop the last element off and call trim to remove any of that pesky whitespace (unless you like your whitespace of course).

"String - Location".split('-').pop().trim(); //"Location"

So using jQuery it would be

$('.v2_review-text').html().split('-').pop().trim(); // "United States"

Or using vanilla JS

var text = document.getElementsByClassName('v2_review-text')[0].innerHTML;
text.split('-').pop().trim(); // "United States"

Solution 3:

Try something like this

str2 = str.substring(str.lastIndexOf("-"))

Solution 4:

The simplest way is probably to use jQuery to get the element, and native JavaScript to get the string:

var fullReview = $('.v2_review-text').text(); //assumes only one review exists, adjust for your use.var country = fullReview.substring(fullReview.lastIndexOf(' - ') + 1); //TODO correct for -1 if ' - ' not found.

This is just a proof of concept; the rest should be relatively easy to figure out. Some things to look up while you're learning: jQuery each

Solution 5:

varval = $('.v2_review-text').text();
var city_array = val.split('-');
var city = city_array[city_array.length - 1];

Hopefully i have helped you buddy.

Post a Comment for "Getting All Characters After The Last '-' In A String"