使用javascript获取两个字符之间的子字符串

我试图从一个更大的字符串中提取一个字符串,它得到:;之间的所有内容

当前的

Str = 'MyLongString:StringIWant;'

期望输出值

newStr = 'StringIWant'
518357 次浏览
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant

使用split()

var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);

arrStr将包含由:;
分隔的所有字符串 因此通过for-loop

访问每个字符串
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);

你可以试试这个

var mySubString = str.substring(
str.indexOf(":") + 1,
str.lastIndexOf(";")
);

你也可以试试这个:

var str = 'one:two;three';
str.split(':').pop().split(';')[0]; // returns 'two'

我喜欢这个方法:

var str = 'MyLongString:StringIWant;';
var tmpStr  = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'

@Babasaheb Gosavi回答是完美的,如果你有一个子字符串出现(“:”和“;”)。但一旦出现多次,就有点棘手了。


我在多个项目中提出的最佳解决方案是在一个对象中使用四个方法。

  • 第一种方法:实际上是从两个字符串之间获取一个子字符串(但是它只会找到一个结果)。
  • 第二种方法:将删除(可能的)最近找到的结果及其前后的子字符串。
  • 第三种方法:将在字符串上递归地执行上述两个方法。
  • 第四个方法:将应用第三个方法并返回结果。

代码

说得够多了,让我们看看代码:

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


// &#34 - 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,'&#34')">Click</button>
  

</div>


</div>

我使用@tsds的方式,但只使用分裂函数。

var str = 'one:two;three';
str.split(':')[1].split(';')[0] // returns 'two'

警告:如果字符串中没有“:”,访问数组的“1”索引将抛出错误!str.split(“:”)[1]

因此,如果存在不确定性,@tsds的方式更安全

str.split(':').pop().split(';')[0]

尝试使用javascript在两个字符之间获取子字符串。

        $("button").click(function(){
var myStr = "MyLongString:StringIWant;";
var subStr = myStr.match(":(.*);");
alert(subStr[1]);
});

取自@ 用jQuery找到两个字符之间的子字符串

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

我做的一个小函数,可以抓取之间的字符串,并且可以(可选地)跳过一些匹配的单词来抓取特定的索引。

同样,将start设置为false将使用字符串的开头,将end设置为false将使用字符串的结尾。

pos1设置为你想要使用的start文本的位置,1将使用start的第一个出现位置

pos2pos1做同样的事情,但是对于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;
}

这可能是可行的解决方案

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)

获取两个子字符串之间的字符串(包含多于1个字符)

function substrInBetween(whole_str, str1, str2){
if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
return undefined; // or ""
}
strlength1 = str1.length;
return whole_str.substring(
whole_str.indexOf(str1) + strlength1,
whole_str.indexOf(str2)
);


}

注意,我使用indexOf()而不是lastIndexOf(),因此它将检查这些字符串的第一次出现

你可以使用更高阶的函数来返回你的提取器的“编译”版本,这样更快。

使用正则表达式,并在闭包中编译一次正则表达式,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也可以帮助你得到你想要替换的值?...

我的回答太长了,但它可能会帮助到一些人!

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

如果您想从一个字符串中提取发生在两个分隔符(不同或相同)之间的所有子字符串,可以使用此函数。它返回一个包含所有子字符串的数组:

function get_substrings_between(str, startDelimiter, endDelimiter)
{
var contents = [];
var startDelimiterLength = startDelimiter.length;
var endDelimiterLength = endDelimiter.length;
var startFrom = contentStart = contentEnd = 0;
    

while(false !== (contentStart = strpos(str, startDelimiter, startFrom)))
{
contentStart += startDelimiterLength;
contentEnd = strpos(str, endDelimiter, contentStart);
if(false === contentEnd)
{
break;
}
contents.push( str.substr(contentStart, contentEnd - contentStart) );
startFrom = contentEnd + endDelimiterLength;
}


return contents;
}


// https://stackoverflow.com/a/3978237/1066234
function strpos(haystack, needle, offset)
{
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
}


// Example usage
var string = "We want to extract all infos (essential ones) from within the brackets (this should be fun).";
var extracted = get_substrings_between(string, '(', ')');
console.log(extracted);
// output: (2) ["essential ones", "this should be fun"]

最初从PHP由raina77ow,移植到Javascript。

var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
if(arr[i] == '['){
var a = '';
for(var j=i+1;j<arr.length;j++){
if(arr[j] == ']'){
var i = j-1;
break;
}else{
a += arr[j];
}
}
myArr.push(a);
}
var operatorsArr = ['+','-','*','/','%'];
if(operatorsArr.includes(arr[i])){
myArr.push(arr[i]);
}
var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
if(numbArr.includes(arr[i])){
var a = '';
for(var j=i;j<arr.length;j++){
if(numbArr.includes(arr[j])){
a += arr[j];
}else{
var i = j-1;
break;
}
}
myArr.push(a);
}
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]

获取所有子字符串。

var out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
out.push(e.replace(':', '').replace(';', ''))
return e;
});
console.log(out[0])
上面的代码适用于简单的例子,但可以帮助… 使用打印稿。< / p >

参数

  • sentence:你想要得到部分的字符串
  • first:开头字符(对于初始示例,它将是:)
  • last:你的部件的最后一个字符(对于初始示例,它将是;)

输出

字符串数组(string[])。如果sentence中没有好的部分,则返回[]

代码

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


这是我刚做的东西。

注意,如果start之后没有找到end,函数将返回start之后的所有内容。它还期望只有一次出现的开始和结束,如果有多次,它将只考虑第一次。

许可:公共领域

/**
* 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 betweenMarkers(text, begin, end) {
var firstChar = text.indexOf(begin) + begin.length;
var lastChar = text.indexOf(end);
var newText = text.substring(firstChar, lastChar);
return newText;
}


console.log(betweenMarkers("MyLongString:StringIWant;",":",";"));