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

当前的

Str = 'MyLongString:StringIWant;'

期望输出值

newStr = 'StringIWant'

当前回答

这是我刚做的东西。

注意,如果在启动后没有找到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);
    });
  });
});

其他回答

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

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

参数

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

输出

字符串数组(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"]

下面是一个可重用的函数,它允许你使返回的子字符串包含或排除,然后可选地修剪它:

function get_substring(full_string, substring_1, substring_2, inclusive, trim)
{
    if (full_string === null) { return null; };
    let substring_1_start = full_string.indexOf(substring_1);
    if (substring_1_start === -1 ) { return null; }
    let substring_2_start = full_string.indexOf(substring_2, substring_1_start);
    if (substring_2_start === -1 ) { return null; }
    let substring_1_end = substring_1_start + substring_1.length;
    let substring_2_end = substring_2_start + substring_2.length;
    let return_string = inclusive ? (full_string.substring(substring_1_start, substring_2_end)) : (full_string.substring(substring_1_end, substring_2_start));
    return trim ? return_string.trim() : return_string;
}

使用例子:

//Returns 'cake and ice cream'
get_substring('I like cake and ice cream', 'cake', 'cream', true, true);

//Returns ' and ice '
get_substring('I like cake and ice cream', 'cake', 'cream', false, false);

//Returns 'and ice'
get_substring('I like cake and ice cream', 'cake', 'cream', false, true);

//Returns null
get_substring('I like cake and ice cream', 'cake', 'cookies', false, false);

//Returns null
get_substring('I like cake and ice cream', null, 'cream', false, false);
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

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

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

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