2017-12-16 9 views
0
MyString = "big BANANA: 5, pineapple(7), small Apples_juice (1,5%)_, oranges* juice 20 %, , other fruit : no number " 

MyStringの各要素の番号を取得したいと思います。javascript/regexで数字を文字列に入力

10進数の区切り文字には、コンマまたはドットを使用できます。

私が試したコード:私はオブジェクトに値を入れて、あなたのコードを書き直すお勧めします

function getValue(string, word) { 
    var index = string.toLowerCase().indexOf(word.toLowerCase()), 
     part = string.slice(index + word.length, string.indexOf(',', index)); 
    return index === -1 ? 'no ' + word + ' found!'    // or throw an exception 
         : part.replace(/[^0-9$.,]/g, ''); 
} 
+0

コード形式 – zabusa

+0

1,5又は1.5を修正しますか?どちらが正しい? – zabusa

+0

https://regex101.com/r/oO3bNy/1おそらく動作する可能性があります(テストケースで動作しますが、数字などが多い数字の場合はおそらく変更する必要があります) – sinisake

答えて

0

誤解されていない場合は、コンマと空白で区切られた部分から数字を取得する場合は、,と入力します。

その場合は、これはオプションであるかもしれない:

  • splitを使用してアレイを作成し、ループの項目
  • チェック言葉はあなたがindexOfを使用してアイテムに存在して探している場合
  • 一致の場合は\d+(?:[.,]\d+)?のようなパターンを使用します。
  • 一致する場合は、それを返します。例えば

var MyString = "big BANANA: 5, pineapple(7), small Apples_juice (1,5%)_, oranges* juice 20 %, , other fruit : no number "; 
 
function getValue(string, word) { 
 
    var items = string.toLowerCase().split(', '); 
 
    word = word.toLowerCase(); 
 
    var pattern = /\d+(?:[.,]\d+)?/g; 
 
    var result = 'no ' + word + ' found!'; 
 
    for (var i = 0; i < items.length; i++) { 
 
     var item = items[i]; 
 
     if (item.indexOf(word) !== -1) { 
 
      var match = item.match(pattern); 
 
      if (match && typeof match[0] !== 'undefined') { 
 
       result = match[0]; 
 
      } 
 
     } 
 
    } 
 
    return result; 
 
} 
 

 
console.log(getValue(MyString, "big BANANA")); 
 
console.log(getValue(MyString, "pineapple")); 
 
console.log(getValue(MyString, "small Apples_juice")); 
 
console.log(getValue(MyString, "oranges* juice")); 
 
console.log(getValue(MyString, "other fruit")); 
 
console.log(getValue(MyString, "ApPle"));

+0

ありがとう、しかし、例えばconsole.log(getValue(MyString、 "ApPle")); - observatoire 1分前に編集 – observatoire

+0

@observatoire私の答えを更新しました。チェックのために '.toLowerCase()'を追加しました。 –

+0

ありがとうございました!あなたの機能は動作します!!! – observatoire

0

:あなたは、その後のためのシンプルなこのmyobj値を反復処理することができます

var myObj = { 
    bigBanana: 5, 
    pineapple: 7, 
    smallApplesJuice: 1.5, 
    ... 
    } 

。 ..ループ中。

これが実現できない場合は、大きな文字列を取得するすべての部分文字列に対してRegExを使用して異なるコードを作成する必要があります。 extracted_valueは、あなたが、その後数に変換する必要があります文字列であることを

//create a regular expression that matches everything after "Apples_juice": 
var re = new RegExp(/((?<=Apples_juice).*$)/); 
//extract three characters that follow "Apples_juice (": 
var extracted_value = MyString.match(re)[0].substring(2,5); 

注:たとえば、Apples_juiceの値を取得するには、これを試してみてください。お役に立てれば。

関連する問題