Palaniichuk Dmytro
Palaniichuk Dmytro

Reputation: 3173

Substring from the end in generic way in javascript

Assume we have such strings.

const del = 'Deleted'
const str1 = 'clean.Deleted'
const str2 = 'get.clean.Deleted'
const str3 = 'cl.Deleted'

And I need return every time str1, str2,str3 without .Deleted

It is work for me:

any_string.substr(0, (any_string.length - del.length-1))

Do we have a more generic way?

Upvotes: 1

Views: 43

Answers (2)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use slice with negative value for slicing from last(.Deleted length is 8, so use -8)

str.slice('.Deleted',-8)

JS:

const del = 'Deleted'
const str1 = 'clean.Deleted'
const str2 = 'get.clean.Deleted'
const str3 = 'cl.Deleted'

console.log(str1.slice('.Deleted',-8))
console.log(str2.slice('.Deleted',-8))
console.log(str3.slice('.Deleted',-8))

Note: This solution works only if the .Deleted is always at the last part of the string

Upvotes: 1

Joseph
Joseph

Reputation: 119847

If .Deleted is always .Deleted, then string.replace

const newString = oldString.replace('.Deleted', '')

You can replace that with RegExp if you only want .Deleted that happens at the end.

const newString = oldString.replace(/\.Deleted$/, '')

Upvotes: 3

Related Questions