283

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

当前的

Str = 'MyLongString:StringIWant;'

期望的输出

newStr = 'StringIWant'
4

23 回答 23

571

你可以试试这个

var mySubString = str.substring(
    str.indexOf(":") + 1, 
    str.lastIndexOf(";")
);
于 2013-02-14T04:39:03.717 回答
173

你也可以试试这个:

var str = 'one:two;three';    
str.split(':').pop().split(';')[0]; // returns 'two'
于 2014-12-17T09:46:53.080 回答
62

采用split()

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

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

for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);
于 2013-02-14T04:35:45.977 回答
45

@Babasaheb Gosavi 如果您出现一次子字符串(“:”和“;”),那么答案是完美的。但是一旦出现多次,它可能会变得有点棘手。


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

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

代码

说了这么多,让我们看看代码:

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}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]
于 2016-08-11T01:22:50.550 回答
29
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
于 2013-02-14T04:35:00.593 回答
24

我喜欢这种方法:

var str = 'MyLongString:StringIWant;';
var tmpStr  = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
于 2016-05-17T21:04:42.957 回答
11

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

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

这使我们只需要删除我们用作标记的内容(即:){{,我们可以将字符串长度与切片一起使用。

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 也可能有助于获取你想要的值用。。。来代替 ? ...

我的答案太长了,但它可能对某人有帮助!

于 2019-10-21T17:01:05.310 回答
9
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
于 2020-01-08T07:21:00.413 回答
7

我使用了@tsds 方式,但只使用了 split 函数。

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

注意:如果字符串中没有“:”,则访问数组的 '1' 索引将引发错误!str.split(':')[1]

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

str.split(':').pop().split(';')[0]
于 2018-03-12T20:24:32.797 回答
2

你也可以用这个...

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>

于 2017-06-01T13:47:00.320 回答
2

使用“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
于 2018-05-26T14:53:36.127 回答
2

这可能是可能的解决方案

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)
于 2019-09-03T07:43:00.890 回答
2

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

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

   }

注意我使用indexOf()而不是lastIndexOf()所以它会检查这些字符串的第一次出现

于 2019-09-19T10:28:16.533 回答
1

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

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

取自@用jQuery查找两个字符之间的子字符串

于 2018-04-18T10:44:31.643 回答
1

我制作的一个小函数可以抓取中间的字符串,并且可以(可选地)跳过一些匹配的单词来抓取特定的索引。

此外,设置startfalse将使用字符串的开头,设置endfalse将使用字符串的结尾。

设置为要使用pos1的文本的位置,将使用第一次出现的start1start

pos2做与 , 相同的事情pos1,但对于end, 并且1将使用end仅 after的第一次出现startendbefore的出现start被忽略。

function getStringBetween(str, start=false, end=false, pos1=1, pos2=1){
  var newPos1 = 0;
  var newPos2 = str.length;

  if(start){
    var loops = pos1;
    var i = 0;
    while(loops > 0){
      if(i > str.length){
        break;
      }else if(str[i] == start[0]){
        var found = 0;
        for(var p = 0; p < start.length; p++){
          if(str[i+p] == start[p]){
            found++;
          }
        }
        if(found >= start.length){
          newPos1 = i + start.length;
          loops--;
        }
      }
      i++;
    }
  }

  if(end){
    var loops = pos2;
    var i = newPos1;
    while(loops > 0){
      if(i > str.length){
        break;
      }else if(str[i] == end[0]){
        var found = 0;
        for(var p = 0; p < end.length; p++){
          if(str[i+p] == end[p]){
            found++;
          }
        }
        if(found >= end.length){
          newPos2 = i;
          loops--;
        }
      }
      i++;
    }
  }

  var result = '';
  for(var i = newPos1; i < newPos2; i++){
    result += str[i];
  }
  return result;
}
于 2019-07-04T15:14:11.280 回答
1

获取所有子字符串。

var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
    out.push(e.replace(':', '').replace(';', ''))
    return e;
});
console.log(out[0])
于 2021-01-13T17:23:20.453 回答
1

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

参数

  • 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"]
于 2021-05-10T19:17:13.627 回答
1

通用且简单:

function betweenMarkers(text, begin, end) {
  var firstChar = text.indexOf(begin) + begin.length;
  var lastChar = text.indexOf(end);
  var newText = text.substring(firstChar, lastChar);
  return newText;
}

console.log(betweenMarkers("MyLongString:StringIWant;",":",";"));

于 2022-01-19T04:34:05.410 回答
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。

于 2020-10-20T19:34:52.813 回答
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"]
于 2020-12-24T12:58:43.813 回答
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"
于 2021-08-06T01:41:36.597 回答
0

这是我刚做的东西。

请注意,该函数将在startif endis not found after 之后返回所有内容start。它还期望只出现一次 start 和 end,如果有多个 - 它只会考虑第一个。

许可证:公共领域

/**
 * Extracts a string from `source` that is placed between `start` and `end`. The function
 * considers only one instance of start and before, or the first instance and does not support
 * multiple occurences otherwise. If end string is not found, it will return everything after
 * `start` to the end of the string.
 */
export function stringBetween(source, start, end) {
  if (source.indexOf(start) === -1) {
    return null;
  }

  const sourceSplitByStartString = source.split(start);

  // Note: If start string is the very first occurence in source string, the result will be an
  // array where the first item is an empty string and the next item is of interest.

  if (
    sourceSplitByStartString.length === 1
    || sourceSplitByStartString[1] === ''
  ) {
    // It means that start is either the entire string or is at the very end of the string, so there
    // is not anything between
    return '';
  }

  const afterStart = sourceSplitByStartString[1];

  // If the after separator is not found, return everything after the start separator to the end
  // of the string
  if (afterStart.indexOf(end) === -1) {
    return afterStart;
  }

  const afterStartSplitByEnd = afterStart.split(end);

  if (afterStartSplitByEnd[0] === '') {
    return '';
  }

  return afterStartSplitByEnd[0];
}

测试:

import { stringBetween } from './string';

describe('string utlities', () => {
  describe('stringBetween', () => {
    it('Extracts a substring between 2 other substrings', () => {
      const sample1 = stringBetween('Black cat climbed the tree fast.', 'cat ', ' the tree');
      expect(sample1).toBe('climbed');

      const sample2 = stringBetween('Black cat climbed the tree fast.', 'Black ', ' fast.');
      expect(sample2).toBe('cat climbed the tree');
    });

    it('extracts everything after start if end is not found', () => {
      const sample2 = stringBetween('Black cat climbed the tree fast.', 'Black ', 'not-there');
      expect(sample2).toBe('cat climbed the tree fast.');
    });

    it('returns empty string if start string occurs at the end', () => {
      const sample = stringBetween('Black cat climbed the tree fast.', 'fast.', 'climbed');
      expect(sample).toBe('');
    });

    it('returns empty string if start string is the entire string', () => {
      const sample = stringBetween('Black cat', 'Black cat', 'climbed');
      expect(sample).toBe('');
    });

    it('returns empty string if there is not anything between start and end', () => {
      const sample = stringBetween('Black cat climbed the tree fast.', 'climbed ', 'the tree');
      expect(sample).toBe('');
    });

    it('returns null if start string does not exist in the source string', () => {
      const sample = stringBetween('Black cat climbed the tree fast.', 'not-there ', 'the tree');
      expect(sample).toBe(null);
    });
  });
});

于 2021-08-16T13:31:22.797 回答
-1

以下函数获得第一个匹配项


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 ")
})

于 2021-08-08T11:47:30.973 回答