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]
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");
// " - 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,'"')">Click</button>
</div>
</div>
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' ]
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"
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
}
Jest测试
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 ")
})
/**
* 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);
});
});
});