Obter o sub-texto entre dois caracteres usando o javascript

estou a tentar extrair uma corda de dentro de uma corda maior onde ela consegue tudo entre um ':' e um ';'.

actual

Str = 'MyLongString:StringIWant;'

Saída Desejada

newStr = 'StringIWant'
Author: Rob, 2013-02-14

10 answers

Podes tentar isto.
var mySubString = str.substring(
    str.lastIndexOf(":") + 1, 
    str.lastIndexOf(";")
);
 249
Author: Babasaheb Gosavi, 2018-06-03 08:02:17

Também podes tentar isto:

var str = 'one:two;three';    
str.split(':').pop().split(';').shift(); // returns 'two'
 59
Author: tsds, 2016-06-30 14:50:20

Utilizar split()

var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);

arrStr irá conter todo o texto delimitado por : ou ;
Então acesse todas as strings através for-loop

for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);
 33
Author: asifsid88, 2013-02-14 04:41:46

@Babasaheb Gosavi resposta é perfeita se você tem uma ocorrência das substrings (":" e ";"). mas uma vez que você tem múltiplas ocorrências, pode ficar um pouco complicado.


A melhor solução que arranjei para trabalhar em vários projectos é usar quatro métodos dentro de um objecto.
  • primeiro método: é realmente obter uma substring de entre duas strings (no entanto, irá encontrar apenas um resultado).
  • segundo método: {[11] } irá remover o (seria) mais recentemente encontrado resultado com as substrings Após e antes dele.
  • terceiro método: fará os dois métodos acima recursivamente numa cadeia de caracteres.
  • Quarto método: irá aplicar o terceiro método e devolver o resultado.

Código

Então chega de conversa, vamos ver o código.
var getFromBetween = {
    results:[],
    string:"",
    getFromBetween:function (sub1,sub2) {
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
        var SP = this.string.indexOf(sub1)+sub1.length;
        var string1 = this.string.substr(0,SP);
        var string2 = this.string.substr(SP);
        var TP = string1.length + string2.indexOf(sub2);
        return this.string.substring(SP,TP);
    },
    removeFromBetween:function (sub1,sub2) {
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
        var removal = sub1+this.getFromBetween(sub1,sub2)+sub2;
        this.string = this.string.replace(removal,"");
    },
    getAllResults:function (sub1,sub2) {
        // first check to see if we do have both substrings
        if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return;

        // find one result
        var result = this.getFromBetween(sub1,sub2);
        // push it to the results array
        this.results.push(result);
        // remove the most recently found one from the string
        this.removeFromBetween(sub1,sub2);

        // if there's more substrings
        if(this.string.indexOf(sub1) > -1 && this.string.indexOf(sub2) > -1) {
            this.getAllResults(sub1,sub2);
        }
        else return;
    },
    get:function (string,sub1,sub2) {
        this.results = [];
        this.string = string;
        this.getAllResults(sub1,sub2);
        return this.results;
    }
};

Como utilizar?

Exemplo:

var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]
 21
Author: Alex C., 2016-08-11 01:22:50
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
 13
Author: otakustay, 2013-02-14 04:35:00

Gosto deste método:

var Str = 'MyLongString:StringIWant;';
var tmpStr  = Str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
 9
Author: Shane Gib., 2016-05-17 21:26:09

Usei o método @tsds, mas usando apenas a função split.

var str = 'one:two;three';    
str.split(':')[1].split(';')[0] // returns 'two'
 2
Author: Timar Ivo Batis, 2018-03-12 20:24:32

Também podes usar este...

function extractText(str,delimiter){
  if (str && delimiter){
    var firstIndex = str.indexOf(delimiter)+1;
    var lastIndex = str.lastIndexOf(delimiter);
    str = str.substring(firstIndex,lastIndex);
  }
  return str;
}


var quotes = document.getElementById("quotes");

// &#34 - represents quotation mark in HTML
<div>


  <div>
  
    <span id="at">
      My string is @between@ the "at" sign
    </span>
    <button onclick="document.getElementById('at').innerText = extractText(document.getElementById('at').innerText,'@')">Click</button>
  
  </div>
  
  <div>
    <span id="quotes">
      My string is "between" quotes chars
    </span>
    <button onclick="document.getElementById('quotes').innerText = extractText(document.getElementById('quotes').innerText,'&#34')">Click</button>
  
  </div>

</div>
 1
Author: Meir Gabay, 2017-06-01 13:47:00

Tente isto para obter sub-texto entre dois caracteres usando javascript.

        $("button").click(function(){
            var myStr = "MyLongString:StringIWant;";
            var subStr = myStr.match(":(.*);");
            alert(subStr[1]);
        });

Retirado de @ encontra substring entre os dois caracteres com jQuery

 0
Author: Ketan Savaliya, 2018-04-18 10:44:31

Usando jQuery:

get_between <- function(str, first_character, last_character) {
    new_str = str.match(first_character + "(.*)" + last_character)[1].trim()
    return(new_str)
    }

Texto

my_string = 'and the thing that ! on the @ with the ^^ goes now' 

Utilização:

get_between(my_string, 'that', 'now')

Resultado:

"! on the @ with the ^^ goes
 0
Author: Cybernetic, 2018-05-26 14:53:36