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.
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);
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])
我只是在Map一词上拆分,然后取第一个索引
var splitUp = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0'.split('Map') var firstPart = splitUp[0]
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('-'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.