简体   繁体   English

从字符串中提取文本直到倒数第二个出现

[英]Extract text until second to last occurrence from string

How do I extract the text from the beginning until (not including) the second to last occurrence of a charachter (":" in this case) from a string?如何从字符串的开头提取文本,直到(不包括)倒数第二次出现字符(在这种情况下为“:”)? Preferably without using regex.最好不使用正则表达式。

Examples:例子:

"urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1" should become "RequestPerformerForAssessmentResponder:1" “urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1”应该变成“RequestPerformerForAssessmentResponder:1”

"urn:riv:itinfra:tp:PingResponder:1" should become "PingResponder:1" “urn:riv:itinfra:tp:PingResponder:1”应该变成“PingResponder:1”

with split function you can parse your string returning an array of the tokens separated from the string in the parameter of split and later you can concatenate last two items in the array使用split function 您可以解析字符串,返回与split参数中的字符串分隔的标记数组,稍后您可以连接数组中的最后两项

 let x = "urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1"; let result = x.split(":"); let yourTextResult = `${result[result.length-2]}:${result[result.length-1]}`; console.log(yourTextResult );

 const data1 = "urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1"; const data2 = "urn:riv:itinfra:tp:PingResponder:1" const arr = data1.split(':'); console.log(arr.splice(arr.length-2,arr.length).join(':'))

 str = 'urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1' split_array = str.split(':') ans = split_array.splice(-2).join(':') console.log('ans', ans) cut_off_part = split_array.join(':') + ':' console.log('cut_off part', cut_off_part)

Another way of doing the same:另一种方法:

 str = 'urn:riv:intygsbestallning:certificate:order:RequestPerformerForAssessmentResponder:1' ans = str.split(':').splice(-2).join(':') console.log("answer", ans) cutoff_part = str.substr(0, str.length - ans.length) console.log("cut_off_part", cutoff_part)

I think this should work, I'm very sure that it is not the best code, but I am sure that you can improve it having it as a base, I hope it will be useful to you我认为这应该可以工作,我很确定它不是最好的代码,但我相信你可以以它为基础改进它,我希望它对你有用

var mainString = "urn:riv:itinfra:tp:PingResponder:1"
var inverseString = reverseString(mainString)
var result = getFinalString(inverseString)
console.log(result)
function reverseString(str){
    return str.split('').reverse().join('')
}
function getFinalString(str){
    var stringAux = str.split(':')
    if(stringAux.length>=2){
        finalString=reverseString(stringAux[0]+':'+stringAux[1])
        return finalString
    }
    return false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM