2016-12-13 14 views
0

この例では、指定した価格を文字列に抽出します。それは宇宙の最後のインデックスを選択するので、上記の方法が動作しません動的文字列に単語を抽出する

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
const price = string.substring(string.lastIndexOf("$")+1,string.lastIndexOf(" ")); 
 
document.write(price);

" "

どのように私は適切な価格の後にスペースを得ることについて行くのですか?


EDIT

文字列は、他の何かかもしれません!私はそれを支配していない、私はちょうど価格を抽出したい。私はそれを明確にしていない場合。

+0

代わりに 'オン' に続くスペースを探します。 – edtheprogrammerguy

+0

私はそれを行うことはできません。なぜなら、価格の後に「オン」という言葉が常に含まれるわけではないからです。 –

答えて

2

正規表現は必ずしも適切なツールではありませんが、この場合は明らかな選択肢のようです。あなたが本当に欲しいのは、$に続く数字とカンマが混在し、他の文字で終わるすべてのものです。

const re = /\$[\d,]+/ 
 
const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
const prices = re.exec(string); 
 
console.log(prices[0]);

ます。また一致する、例えば、パターンを拡張したい場合があります.から/\$[\d,.]+(「$ 5,000.25」キャプチャします)またはスペースが、余分な許容、何でもします: /\$[^ ]+/( "$ tonsofmoney"をキャプチャします)。

+0

私は具体的に言及していないにもかかわらずあなたの答えを受け入れました。動的文は、価格の後にピリオド「。」を含むことがあります。私は手を汚して、私が推測するいくつかの正規表現を研究しなければならない! –

2
const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
    const price =string.split('$')[1]//text after $ 
      .split(' ')[0];// text after $ and before space 
    document.write(price); 

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
const price =string.split('$')[1].split(' ')[0]; 
 
document.write(price);

または

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
    const price =string.match(/\$[0-9]*,[0-9]*/); 
 
//match $XXX,XXX in the string and estract it 
 
    document.write(price);

+0

上記のコードの仕組みを簡単に説明できますか?ありがとうございました編集:2番目の方法は動作しません!私が言及したように、私に与えられた文字列は、毎回同じではない動的な手段です。 –

+1

ok私は答えを更新します –

0

あなたはstring.split()

0123を使用することができます

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
const price = (string.split('$')[1]).split(' ')[0]; 
 
document.write(price);

これは$の最初のインデックスで文字列を分割し、$の後に参加しています。
これは、スペースの最初の出現時に文字列を分割し、スペースの前の部分を取ります。

これは、文字列に$記号が1つしかないと予想していることに注意してください。

1

これを試してください。私はそれを複数の行に分割して読みやすくしています。

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
 
var dollarPosition = string.lastIndexOf("$"); 
 
var nextSpace = string.indexOf(" ", dollarPosition+1); 
 
const price = string.substring(dollarPosition+1,nextSpace); 
 
document.write(price);

+0

この方法はこのケースでは完璧に機能します。ステップに分割していただきありがとうございます。 –

2

あなたは試すことができます:

const string = 'I am a long sentence! My price is $5,000 on a discount!'; 
const price = (string.split("$")[1].split(" ")[0]); 
document.write(price); 
1

const string = 'I am a long sentence! My price is $5,000 on a discount!' + 
 
    'Another price: $120.'; 
 

 
var m = string.match(/\$[\d,]+/g); 
 
var i, price; 
 
if (m) { 
 
    for (i = 0; i < m.length; i++) { 
 
    price = m[i].replace('$', ''); 
 
    console.log(price); 
 
    } 
 
}

関連する問題