:
aと a の間のすべてを取得する大きな文字列内から文字列を抽出しようとしています;
現時点の
Str = 'MyLongString:StringIWant;'
望ましい出力
newStr = 'StringIWant'
:
aと a の間のすべてを取得する大きな文字列内から文字列を抽出しようとしています;
現時点の
Str = 'MyLongString:StringIWant;'
望ましい出力
newStr = 'StringIWant'
これを試すことができます
var mySubString = str.substring(
str.indexOf(":") + 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 Answer は、部分文字列 (":" と ";") が 1 つある場合に最適です。しかし、複数のオカレンスがあると、少し注意が必要になる場合があります。
複数のプロジェクトに取り組むために私が思いついた最善の解決策は、オブジェクト内で 4 つのメソッドを使用することです。
話は十分なので、コードを見てみましょう。
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'
これも使えます...
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>
「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
一般的でシンプル:
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;",":",";"));
ここに私が作ったものがあります。
が after に見つからないstart
場合、関数は after のすべてを返すことに注意してください。また、start と end が 1 回だけ出現することも想定しており、複数ある場合は最初のもののみを考慮します。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);
});
});
});
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"]