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

当前的

Str = 'MyLongString:StringIWant;'

期望输出值

newStr = 'StringIWant'

当前回答

下面的函数获取第一个匹配项


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

其他回答

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

获取所有子字符串。

var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
    out.push(e.replace(':', '').replace(';', ''))
    return e;
});
console.log(out[0])

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

这是我刚做的东西。

注意,如果在启动后没有找到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 str = 'MyLongString:StringIWant;';
var tmpStr  = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'