我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;
当前的
Str = 'MyLongString:StringIWant;'
期望输出值
newStr = 'StringIWant'
我试图从一个更大的字符串中提取一个字符串,它得到了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);
});
});
});
其他回答
使用' 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
上面的代码适用于简单的例子,但可以帮助… 使用打印稿。
参数
句子:你想要得到部分的字符串 第一个:开头字符(对于初始示例,它将是:) 最后:你的部分的最后一个字符(对于初始示例,它将是;)
输出
字符串数组(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 betweenMarkers(text, begin, end) { var firstChar = text.indexOf(begin) + begin.length; var lastChar = text.indexOf(end); var newText =文本。substring (firstChar lastChar); 返回newText; } console.log (betweenMarkers(“MyLongString: StringIWant ;",":",";"));
使用分割()
var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);
arrStr将包含所有由:或; 通过for循环访问每个字符串
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);
你可以使用更高阶的函数来返回你的提取器的“编译”版本,这样更快。
使用正则表达式,并在闭包中编译一次正则表达式,Javascript的匹配将返回所有匹配项。
这让我们只需要删除我们用作标记的东西(例如:{{),我们可以使用字符串长度来实现slice。
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也可以帮助你得到你想要替换的值?...
我的回答太长了,但它可能会帮助到一些人!