Javascript 使用javascript获取两个字符之间的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14867835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Substring between two characters using javascript
提问by Rob
I am trying to extract a string from within a larger string where it get everything inbetween a ':' and a ';'.
我试图从一个更大的字符串中提取一个字符串,它在':'和';'之间获取所有内容。
Current
当前的
Str = 'MyLongString:StringIWant;'
Desired Output
期望输出
newStr = 'StringIWant'
回答by Babasaheb Gosavi
You can try this
你可以试试这个
var mySubString = str.substring(
str.lastIndexOf(":") + 1,
str.lastIndexOf(";")
);
回答by tsds
You can also try this:
你也可以试试这个:
var str = 'one:two;three';
str.split(':').pop().split(';')[0]; // returns 'two'
回答by asifsid88
Use split()
用 split()
var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);
arrStrwill contain all the string delimited by :or ;
So access every string through for-loop
arrStr将包含由:or分隔的所有字符串;
所以通过访问每个字符串for-loop
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);
回答by Alex C.
@Babasaheb Gosavi Answer is perfect if you have one occurrence of the substrings (":" and ";"). but once you have multiple occurrences, it might get little bit tricky.
@Babasaheb Gosavi 如果您有一次出现子字符串(“:”和“;”),则答案是完美的。但是一旦出现多次,它可能会变得有点棘手。
The best solution I have came up with to work on multiple projects is using four methods inside an object.
我想出的处理多个项目的最佳解决方案是在一个对象中使用四种方法。
- First method:is to actually get a substring from between two strings (however it will find only one result).
- Second method:will remove the (would-be) most recently found result with the substrings after and before it.
- Third method:will do the above two methods recursively on a string.
- Fourth method:will apply the third method and return the result.
- 第一种方法:实际上是从两个字符串之间获取一个子字符串(但是它只会找到一个结果)。
- 第二种方法:将删除(可能)最近找到的结果及其前后的子字符串。
- 第三种方法:将在字符串上递归执行上述两种方法。
- 第四种方法:将应用第三种方法并返回结果。
Code
代码
So enough talking, let's see the 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;
}
};
How to use?
如何使用?
Example:
例子:
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]
回答by otakustay
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
回答by Shane Gib.
I like this method:
我喜欢这个方法:
var str = 'MyLongString:StringIWant;';
var tmpStr = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
回答by Timar Ivo Batis
I used @tsds way but by only using the split function.
我使用了@tsds 方式,但只使用了 split 功能。
var str = 'one:two;three';
str.split(':')[1].split(';')[0] // returns 'two'
word of caution: if therre is no ":" in the string accessing '1' index of the array will throw an error! str.split(':')[1]
注意事项:如果字符串中没有“:”,访问数组的 '1' 索引将抛出错误!str.split(':')[1]
therefore @tsds way is safer if there is uncertainty
因此,如果存在不确定性,@tsds 方式会更安全
str.split(':').pop().split(';')[0]
回答by Ooki Koi
You can use a higher order function to return a 'compiled' version of your extractor, that way it's faster.
您可以使用高阶函数来返回提取器的“编译”版本,这样速度会更快。
With regexes, and compiling the regex once in a closure, Javascript's match will return all matches.
使用正则表达式,并在闭包中编译一次正则表达式,Javascript 的匹配将返回所有匹配。
This leaves us with only having to remove what we used as our markers (ie: {{) and we can use string length for this with slice.
这让我们只需要删除我们用作标记的内容(即:){{,我们可以使用字符串长度来使用 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);
}
}
Compile once and use multiple times...
编译一次,多次使用...
const stringExtractor = extract(['{','}']);
const stuffIneed = stringExtractor('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Or single-time use...
或者一次性使用...
const stuffIneed = extract(['{','}'])('this {is} some {text} that can be {extracted} with a {reusable} function');
// Outputs: [ 'is', 'text', 'extracted', 'reusable' ]
Also look at Javascript's replacefunction but using a function for the replacement argument (You would do that if for example you were doing a mini template engine (string interpolation) ... lodash.get could also be helpful then to get the values you want to replace with ? ...
还可以查看 Javascript 的replace函数,但使用替换参数的函数(例如,如果您正在做一个迷你模板引擎(字符串插值),您会这样做...... lodash.get 也可能有助于获取您想要的值用。。。来代替 ? ...
My answer is too long but it might help someone!
我的答案太长了,但它可能对某人有所帮助!
回答by bianbian
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
回答by Meir Gabay
You can also use this one...
你也可以用这个...
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>

