我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;
当前的
Str = 'MyLongString:StringIWant;'
期望输出值
newStr = 'StringIWant'
我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;
当前的
Str = 'MyLongString:StringIWant;'
期望输出值
newStr = 'StringIWant'
当前回答
一般的和简单的:
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 ;",":",";"));
其他回答
下面是一个可重用的函数,它允许你使返回的子字符串包含或排除,然后可选地修剪它:
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);
我做的一个小函数,可以抓取之间的字符串,并且可以(可选地)跳过一些匹配的单词来抓取特定的索引。
同样,将start设置为false将使用字符串的开头,将end设置为false将使用字符串的结尾。
将pos1设置为您想要使用的开始文本的位置,1将使用start的第一次出现
Pos2和pos1做同样的事情,但是对于end,并且1将只在start之后使用end的第一次出现,在start之前出现的end将被忽略。
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;
}
这是我刚做的东西。
注意,如果在启动后没有找到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
下面的函数获取第一个匹配项
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 ")
})