我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;
当前的
Str = 'MyLongString:StringIWant;'
期望输出值
newStr = 'StringIWant'
我试图从一个更大的字符串中提取一个字符串,它得到了a:和a之间的所有东西;
当前的
Str = 'MyLongString:StringIWant;'
期望输出值
newStr = 'StringIWant'
当前回答
尝试使用javascript在两个字符之间获取子字符串。
$("button").click(function(){
var myStr = "MyLongString:StringIWant;";
var subStr = myStr.match(":(.*);");
alert(subStr[1]);
});
从@ Find子字符串之间的两个字符与jQuery
其他回答
这是我刚做的东西。
注意,如果在启动后没有找到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);
});
});
});
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
这可能是可行的解决方案
var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'
console.log('stringvalue',newstr)
@Babasaheb Gosavi回答是完美的,如果你有一个子字符串出现(“:”和“;”)。但一旦出现多次,就有点棘手了。
我在多个项目中提出的最佳解决方案是在一个对象中使用四个方法。
第一种方法:实际上是从两个字符串之间获得一个子字符串(但是它只会找到一个结果)。 第二种方法:删除(可能的)最近发现的结果及其前后的子字符串。 第三种方法:将上述两种方法递归地处理一个字符串。 第四种方法:将应用第三种方法并返回结果。
Code
说得够多了,让我们看看代码:
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 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 ")
})