我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;

当前的

Str = 'MyLongString:StringIWant;'

期望输出值

newStr = 'StringIWant'

当前回答

尝试使用javascript在两个字符之间获取子字符串。

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

从@ Find子字符串之间的两个字符与jQuery

其他回答

你也可以用这个…

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>

我使用@tsds的方式,但只使用分裂函数。

var str = 'one:two;three';    
str.split(':')[1].split(';')[0] // returns 'two'

警告:如果字符串中没有“:”,访问数组的“1”索引将抛出错误!str.split(“:”)[1]

因此,如果存在不确定性,@tsds的方式更安全

str.split(':').pop().split(';')[0]

使用分割()

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

arrStr将包含所有由:或; 通过for循环访问每个字符串

for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);

使用' get_between '实用函数:

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

字符串

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

用法:

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

结果:

"! on the @ with the ^^ goes

获取两个子字符串之间的字符串(包含多于1个字符)

function substrInBetween(whole_str, str1, str2){
   if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
       return undefined; // or ""
  }
  var strlength1 = str1.length;
  return whole_str.substring(
                whole_str.indexOf(str1) + strlength1, 
                whole_str.indexOf(str2)
               );

   }

注意,我使用indexOf()而不是lastIndexOf(),因此它将检查这些字符串的第一次出现