使用javascript获取两个字符之间的子串

时间:2013-02-14 04:31:42

标签: javascript regex string substring

我正在尝试从一个更大的字符串中提取一个字符串,它在“:”和“;”之间获取所有内容。

当前

Str = 'MyLongString:StringIWant;'

期望输出

newStr = 'StringIWant'

22 个答案:

答案 0 :(得分:300)

你可以试试这个

var mySubString = str.substring(
    str.lastIndexOf(":") + 1, 
    str.lastIndexOf(";")
);

答案 1 :(得分:70)

你也可以试试这个:

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

答案 2 :(得分:38)

使用split()

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

arrStr将包含:;分隔的所有字符串 因此,请通过for-loop

访问每个字符串
for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);

答案 3 :(得分:25)

@Babasaheb Gosavi如果您有一次子串(&#34;:&#34;和#34 ;;&#34;),答案是完美的。但是一旦你有多次出现,它可能会有点棘手。

我提出的处理多个项目的最佳解决方案是在对象中使用四种方法。

  • 第一种方法:实际上是从两个字符串之间获取子字符串(但是它只会找到一个结果)。
  • 第二种方法:会删除(可能)最近找到的带有子串的结果。
  • 第三种方法:将在字符串上递归执行上述两种方法。
  • 第四种方法:将应用第三种方法并返回结果。

代码

说得够多,让我们看看代码:

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;
    }
};

如何使用?

实施例

var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {MutationObserver} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]

答案 4 :(得分:16)

var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant

答案 5 :(得分:9)

我喜欢这种方法:

var Str = 'MyLongString:StringIWant;';
var tmpStr  = Str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'

答案 6 :(得分:6)

function substringBetween(s, a, b) {
    var p = s.indexOf(a) + a.length;
    return s.substring(p, s.indexOf(b, p));
}

// substringBetween('MyLongString:StringIWant;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;:StringIDontWant;', ':', ';') -> StringIWant

答案 7 :(得分:3)

我使用了@tsds方式,但只使用了分割功能。

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

警告:如果不是&#34;:&#34;在字符串中访问&#39; 1&#39;数组的索引会抛出错误! str.split(&#39;:&#39;)[1]

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

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

答案 8 :(得分:1)

这可能是解决方案

var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';  
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'

console.log('stringvalue',newstr)

答案 9 :(得分:1)

获取所有子字符串。

Functions:

        H: [GET,POST] http://localhost:7071/api/route/{route}

        Activity1: activityTrigger

        Or1: orchestrationTrigger

For detailed output, run func with --verbose flag.
[2021-01-13T16:17:06.841Z] Host lock lease acquired by instance ID '000000000000000000000000EB8F9C93'.
[2021-01-13T16:17:24.767Z] Executing 'H' (Reason='This function was programmatically called via the host APIs.', Id=0aeee0e1-6148-4c21-9aa9-d17a43bce8d1)
[2021-01-13T16:17:24.925Z] Executed 'H' (Succeeded, Id=0aeee0e1-6148-4c21-9aa9-d17a43bce8d1, Duration=164ms)
[2021-01-13T16:17:24.995Z] Executing 'Or1' (Reason='(null)', Id=6aa97b04-d526-41b1-9532-afb21c088b18)
[2021-01-13T16:17:25.006Z] *********time now 1/13/2021 4:17:24 PM
[2021-01-13T16:17:25.007Z] *********endTime 1/13/2021 4:17:54 PM
[2021-01-13T16:17:25.017Z] Executed 'Or1' (Succeeded, Id=6aa97b04-d526-41b1-9532-afb21c088b18, Duration=23ms)
[2021-01-13T16:18:16.476Z] Executing 'Or1' (Reason='(null)', Id=9749d719-5789-419a-908f-6523cf497cca)
[2021-01-13T16:18:16.477Z] *********time now 1/13/2021 4:17:24 PM
[2021-01-13T16:18:16.478Z] *********endTime 1/13/2021 4:17:54 PM
[2021-01-13T16:18:16.481Z] *********endTime finish 1/13/2021 4:18:16 PM
[2021-01-13T16:18:16.485Z] Executed 'Or1' (Succeeded, Id=9749d719-5789-419a-908f-6523cf497cca, Duration=9ms)

答案 10 :(得分:1)

您可以使用更高阶的函数来返回提取器的“已编译”版本,这样会更快。

使用正则表达式,并且在关闭时编译一次正则表达式,Javascript的match将返回所有匹配项。

这使我们只需要删除用作标记的内容(即{{),就可以在切片中使用字符串长度了。

function extract([beg, end]) {
    const matcher = new RegExp(`${beg}(.*?)${end}`,'gm');
    const normalise = (str) => str.slice(beg.length,end.length*-1);
    return function(str) {
        return str.match(matcher).map(normalise);
    }
}

编译一次并使用多次...

const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]

或一次性使用...

const stuffIneed = extract(['{','}'])('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]

还要看一下Javascript的replace函数,但是要使用一个函数作为替换参数(例如,如果您正在使用小型模板引擎(字符串插值),则可以这样做... lodash.get也可能会有所帮助然后获取您要替换为?的值...

我的回答太长,但可能会对某人有所帮助!

答案 11 :(得分:1)

在子字符串之间获取字符串(包含超过1个字符)

function substrInBetween(whole_str, str1, str2){
  strlength1 = str1.length;
  return whole_str.substring(
                whole_str.indexOf(str1) + strlength1, 
                whole_str.indexOf(str2)
               );

   }

请注意,我使用indexOf()代替了lastIndexOf(),因此它将检查这些字符串的首次出现情况

答案 12 :(得分:1)

使用 jQuery

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

答案 13 :(得分:1)

你也可以使用这个......

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>

答案 14 :(得分:0)

我制作的一个小函数,可以捕获之间的字符串,并且可以(可选)跳过多个匹配的单词以捕获特定的索引。

另外,将start设置为false将使用字符串的开头,将end设置为false将使用字符串的结尾。

pos1设置为要使用的start文本的位置,1将使用第一个出现的start

pos2pos1的作用相同,但对于end1仅在{{1}之后使用end的第一次出现},将忽略start之前end的出现。

start

答案 15 :(得分:0)

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

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

取自@ Find substring between the two characters with jQuery

答案 16 :(得分:0)

 var number = 200
 if (number >= 500 || number <= 600){
    alert("your message");
 }

答案 17 :(得分:0)

如果要从字符串中提取出现在两个定界符(不同或相同)之间的所有子字符串,则可以使用此函数。它返回一个包含所有子字符串的数组:

function get_substrings_between(str, startDelimiter, endDelimiter) 
{
    var contents = [];
    var startDelimiterLength = startDelimiter.length;
    var endDelimiterLength = endDelimiter.length;
    var startFrom = contentStart = contentEnd = 0;
    
    while(false !== (contentStart = strpos(str, startDelimiter, startFrom))) 
    {
        contentStart += startDelimiterLength;
        contentEnd = strpos(str, endDelimiter, contentStart);
        if(false === contentEnd) 
        {
            break;
        }
        contents.push( str.substr(contentStart, contentEnd - contentStart) );
        startFrom = contentEnd + endDelimiterLength;
    }

    return contents;
}

// https://stackoverflow.com/a/3978237/1066234
function strpos(haystack, needle, offset) 
{
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

// Example usage
var string = "We want to extract all infos (essential ones) from within the brackets (this should be fun).";
var extracted = get_substrings_between(string, '(', ')');
console.log(extracted); 
// output: (2) ["essential ones", "this should be fun"]

最初是通过raina77ow从PHP移植到Javascript的。

答案 18 :(得分:0)

var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
    if(arr[i] == '['){
        var a = '';
        for(var j=i+1;j<arr.length;j++){
            if(arr[j] == ']'){
                var i = j-1;
                break;
            }else{
                a += arr[j];
            }
        }
        myArr.push(a);
    }
    var operatorsArr = ['+','-','*','/','%'];
    if(operatorsArr.includes(arr[i])){
        myArr.push(arr[i]);
    }
    var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
    if(numbArr.includes(arr[i])){
        var a = '';
        for(var j=i;j<arr.length;j++){
            if(numbArr.includes(arr[j])){
                a += arr[j];
            }else{
                var i = j-1;
                break;
            }
        }
        myArr.push(a);
    }
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]

答案 19 :(得分:0)

上面的代码适用于简单的示例,但可以帮助... 使用打字稿。

参数

  • sentence : 你想要获取部分的字符串
  • first :开始字符(对于初始示例,它是 :
  • last :你的部分的最后一个字符(对于最初的例子,它是 ;

输出

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

代码

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"]

答案 20 :(得分:0)

您可以使用此功能-

function getStringInBetween(string, start , end) {
    // start and end will be excluded
    var indexOfStart = string.indexOf(start)
    indexOfStart = indexOfStart + start.length;
    var newString = string.slice(indexOfStart)
    var indexOfEnd = newString.indexOf(end)
    return newString.slice(0, indexOfEnd)
}

例如 -

let string = "<div class = 'mice'> I know how to code </div>"
let start = "<div class = 'mice'> "
let end = " </div>"
//then, getStringInBetween(string, start, end) returns "I know how to code"

答案 21 :(得分:0)

Following Function 获得第一个匹配


function getStringBetween(x: string, start: string, end: string) {
  const regex = new RegExp(`${start}(.*?)${end}`)

  if (regex.test(x)) {
    return regex.exec(x)![1]
  } else return undefined
}

玩笑测试


test("getStringBetween", () => {
  const result = getStringBetween("<em> Jai Ram</em>", "<em>", "</em>")
  expect(result).toEqual(" Jai Ram")
  const result1 = getStringBetween(
    "hare Jai Ram hare hare hare",
    "hare",
    "hare"
  )
  expect(result1).toEqual(" Jai Ram ")
})