Reputation: 6316
I have a dynamically generated text like this
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...
? I know there is a hard coded way to do this by using substring()
but as I said these strings are dynamic and before Map ..
can change so I need to do this dynamically by removing everything before 4th
index of -
character.
Upvotes: 1
Views: 896
Reputation: 92440
I would just find the index of Map
and use it to slice the string:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let ind = str.indexOf("Map")
console.log(str.slice(ind))
If you prefer a regex (or you may have occurrences of Map
in the prefix) you man match exactly what you want with:
let str = "xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0"
let arr = str.match(/^(?:.+?-){4}(.*)/)
console.log(arr[1])
Upvotes: 3
Reputation: 10729
Uses String.replace
with regex expression should be the popular solution.
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.
,
I think another solution is split('-')
first, then join the strings after 4th -
.
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'
console.log(test.split('-').slice(4).join('-'))
Upvotes: 0
Reputation: 1158
I would just split on the word Map and take the first index
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map')
var firstPart = splitUp[0]
Upvotes: 0
Reputation: 386600
You could remove all four minuses and the characters between from start of the string.
var string = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0',
stripped = string.replace(/^([^-]*-){4}/, '');
console.log(stripped);
Upvotes: 4