283

:aと a の間のすべてを取得する大きな文字列内から文字列を抽出しようとしています;

現時点の

Str = 'MyLongString:StringIWant;'

望ましい出力

newStr = 'StringIWant'
4

23 に答える 23

571

これを試すことができます

var mySubString = str.substring(
    str.indexOf(":") + 1, 
    str.lastIndexOf(";")
);
于 2013-02-14T04:39:03.717 に答える
173

これを試すこともできます:

var str = 'one:two;three';    
str.split(':').pop().split(';')[0]; // returns 'two'
于 2014-12-17T09:46:53.080 に答える
62

使用する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]);
于 2013-02-14T04:35:45.977 に答える
45

@Babasaheb Gosavi Answer は、部分文字列 (":" と ";") が 1 つある場合に最適です。しかし、複数のオカレンスがあると、少し注意が必要になる場合があります。


複数のプロジェクトに取り組むために私が思いついた最善の解決策は、オブジェクト内で 4 つのメソッドを使用することです。

  • 最初の方法:実際に 2 つの文字列の間から部分文字列を取得することです (ただし、結果は 1 つしか見つかりません)。
  • 2 番目の方法:前後の部分文字列を使用して、最近見つかった (可能性のある) 最新の結果を削除します。
  • 3 番目の方法:上記の 2 つの方法を文字列に対して再帰的に実行します。
  • 4 番目の方法: 3 番目の方法を適用し、結果を返します。

コード

話は十分なので、コードを見てみましょう。

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]
于 2016-08-11T01:22:50.550 に答える
29
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant
于 2013-02-14T04:35:00.593 に答える
24

私はこの方法が好きです:

var str = 'MyLongString:StringIWant;';
var tmpStr  = str.match(":(.*);");
var newStr = tmpStr[1];
//newStr now contains 'StringIWant'
于 2016-05-17T21:04:42.957 に答える
2

これも使えます...

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>

于 2017-06-01T13:47:00.320 に答える
2

「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
于 2018-05-26T14:53:36.127 に答える
1

一般的でシンプル:

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

于 2022-01-19T04:34:05.410 に答える
0

ここに私が作ったものがあります。

が after に見つからないstart場合、関数は after のすべてを返すことに注意してください。また、start と end が 1 回だけ出現することも想定しており、複数ある場合は最初のもののみを考慮します。endstart

ライセンス: パブリック ドメイン

/**
 * 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);
    });
  });
});

于 2021-08-16T13:31:22.797 に答える
0
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"]
于 2020-12-24T12:58:43.813 に答える