![](/img/trans.png)
[英]Get substring between two special characters using javascript
[英]Get Substring between two characters using javascript
我试图从一个更大的字符串中提取一个字符串,它在一个:
和一个;
之间获取所有内容。
当前的
Str = 'MyLongString:StringIWant;'
所需 Output
newStr = 'StringIWant'
你可以试试这个
var mySubString = str.substring(
str.lastIndexOf(":") + 1,
str.lastIndexOf(";")
);
你也可以试试这个:
var str = 'one:two;three';
str.split(':').pop().split(';')[0]; // returns 'two'
使用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]);
@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]
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
我喜欢这个方法:
var str = 'MyLongString:StringIWant;';
var tmpStr = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
您可以使用高阶函数来返回提取器的“编译”版本,这样速度会更快。
使用正则表达式,并在闭包中编译一次正则表达式,Javascript 的匹配将返回所有匹配。
这让我们只需要删除我们用作标记的内容(即: {{
),我们可以使用字符串长度与切片。
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
我使用了@tsds 方式,但只使用了 split 功能。
var str = 'one:two;three';
str.split(':')[1].split(';')[0] // returns 'two'
注意事项:如果字符串中没有“:”,访问数组的 '1' 索引将抛出错误! str.split(':')[1]
因此,如果存在不确定性,@tsds 方式会更安全
str.split(':').pop().split(';')[0]
你也可以用这个...
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>
这可能是可能的解决方案
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 在两个字符之间获取子字符串。
$("button").click(function(){
var myStr = "MyLongString:StringIWant;";
var subStr = myStr.match(":(.*);");
alert(subStr[1]);
});
使用jQuery :
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
pos2
做同样的事情pos1
,但end
,和1
将使用第一次出现end
后才start
,的出现end
之前start
被忽略。
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 out = []; 'MyLongString:StringIWant;'
.replace(/(:)\w+(;)+/g, (e) => {
out.push(e.replace(':', '').replace(';', ''))
return e;
});
console.log(out[0])
上面的代码适用于简单的示例,但可以帮助...使用 Typescript。
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 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"]
最初由Raina77ow从 PHP 移植到 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"]
您可以使用此功能-
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"
这是我刚做的东西。
请注意,如果在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;",":",";"));
这是一个可重复使用的 function,它允许您使返回的 substring 包含或排除,并可选择在之后修剪它:
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);
let substring_2_start = full_string.indexOf(substring_2);
if (substring_1_start === -1 || 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);
我试图从一个较大的字符串中提取一个字符串,该字符串将a :
和a之间的所有内容都包含在内;
当前的
Str = 'MyLongString:StringIWant;'
期望的输出
newStr = 'StringIWant'
以下函数获得第一个匹配项
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 ")
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.