[英]How to remove strings before nth character in a text?
I have a dynamically generated text like this 我有这样的动态生成的文本
xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0
How can I remove everything before Map ...
? 如何删除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. 我知道有通过做这个硬编码的方式substring()
但正如我所说的这些字符串是动态的,之前Map ..
可以改变,所以我需要通过删除之前的一切动态地做到这一点4th
的指标-
字符。
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: 我只是找到Map
的索引,并用它来切片字符串:
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: 如果您喜欢使用正则表达式(或者前缀中可能包含Map
),则可以完全匹配所需的内容:
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. 在正则表达式中使用String.replace
应该是流行的解决方案。
Based on the OP states: so I need to do this dynamically by removing everything before 4th index of - character.
基于OP状态: 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 -
. 我认为,另一种解决方案是split('-')
然后再加入4后弦-
let test = 'xxxxxx-xxxx-xxxxx-xxxxx-Map-B-844-0' console.log(test.split('-').slice(4).join('-'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.