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

当前的

Str = 'MyLongString:StringIWant;'

期望输出值

newStr = 'StringIWant'

当前回答

我使用@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]);

获取两个子字符串之间的字符串(包含多于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(),因此它将检查这些字符串的第一次出现

你也可以用这个…

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>

上面的代码适用于简单的例子,但可以帮助… 使用打印稿。

参数

句子:你想要得到部分的字符串 第一个:开头字符(对于初始示例,它将是:) 最后:你的部分的最后一个字符(对于初始示例,它将是;)

输出

字符串数组(string[])。如果句子中没有好的部分,则返回[]。

Code

function getParts(sentence: string, first: string, last: string): string[] { 
  let goodParts: string[] = [];
  
  const allParts = sentence.split(first);

  allParts.forEach((part: string) => {
    if (part.indexOf(last) > -1) {
            const goodOne = (part.split(last))[0];
      goodParts = goodParts.concat(goodOne);
    }
  });
  
  return goodParts;
}

例子

const origin = "wrongString1:rightString1;wrongString2:rightString2;wrongString3:rightString3;wrongString4:rightString4;";

const result = getParts(origin, ':', ';');

console.log(result);
// ["rightString1", "rightString2", "rightString3", "rightString4"]

使用' 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