What would be the cleanest way of doing this that would work in both IE and firefox.
My string looks like this: sometext-20202
Now the \'sometext\' and the
myString.split('-').splice(1).join('-')
I came to this question because I needed what OP was asking but more than what other answers offered (they're technically correct, but too minimal for my purposes). I've made my own solution; maybe it'll help someone else.
Let's say your string is 'Version 12.34.56'
. If you use '.'
to split, the other answers will tend to give you '56'
, when maybe what you actually want is '.34.56'
(i.e. everything from the first occurrence instead of the last, but OP's specific case just so happened to only have one occurrence). Perhaps you might even want 'Version 12'
.
I've also written this to handle certain failures (like if null
gets passed or an empty string, etc.). In those cases, the following function will return false
.
splitAtSearch('Version 12.34.56', '.') // Returns ['Version 12', '.34.56']
/**
* Splits string based on first result in search
* @param {string} string - String to split
* @param {string} search - Characters to split at
* @return {array|false} - Strings, split at search
* False on blank string or invalid type
*/
function splitAtSearch( string, search ) {
let isValid = string !== '' // Disallow Empty
&& typeof string === 'string' // Allow strings
|| typeof string === 'number' // Allow numbers
if (!isValid) { return false } // Failed
else { string += '' } // Ensure string type
// Search
let searchIndex = string.indexOf(search)
let isBlank = (''+search) === ''
let isFound = searchIndex !== -1
let noSplit = searchIndex === 0
let parts = []
// Remains whole
if (!isFound || noSplit || isBlank) {
parts[0] = string
}
// Requires splitting
else {
parts[0] = string.substring(0, searchIndex)
parts[1] = string.substring(searchIndex)
}
return parts
}
splitAtSearch('') // false
splitAtSearch(true) // false
splitAtSearch(false) // false
splitAtSearch(null) // false
splitAtSearch(undefined) // false
splitAtSearch(NaN) // ['NaN']
splitAtSearch('foobar', 'ba') // ['foo', 'bar']
splitAtSearch('foobar', '') // ['foobar']
splitAtSearch('foobar', 'z') // ['foobar']
splitAtSearch('foobar', 'foo') // ['foobar'] not ['', 'foobar']
splitAtSearch('blah bleh bluh', 'bl') // ['blah bleh bluh']
splitAtSearch('blah bleh bluh', 'ble') // ['blah ', 'bleh bluh']
splitAtSearch('$10.99', '.') // ['$10', '.99']
splitAtSearch(3.14159, '.') // ['3', '.14159']
A solution I prefer would be:
const str = 'sometext-20202';
const slug = str.split('-').pop();
Where slug
would be your result