2017-10-15 14 views
2

私はJavaScriptを初めて使用しています。私は文字列の中で特定の文字列をどのように引き出すことができるのかちょっと分かりません。明確にするために、私は以下の例でmyare delicious.を削除し、2つの間のテキストのみを返します。できるだけ長い間、jQueryは必要ありません。JavaScript:文字列内の特定の文字列を引き出します。

'my cheesecakes are delicious.' 'cheesecakes'

'my salad and sandwiches are delicious.' 'salad and sandwiches'

'my tunas are delicious.' 'tunas'

+2

を使用できるようにすることを歓迎。試行された解決策、失敗した理由、および予想される結果を含めてください。それは本当にあなたのコードの問題を理解するのに役立ちます。ありがとう! –

答えて

1

あなたは.indexOf().substr()方法

var text = 'my cheesecakes are delicious.'; 

var from = text.indexOf('my'); 

var to = text.indexOf('are delicious.') 

var final = text.substr(from + 'my'.length, to - 'my'.length); 

final = final.trim(); // cut spaces before and after string 

console.log(final); 
+0

遅い回答をおかけして申し訳ありませんが、私はあなたの答えを試してみました。 ;) –

+0

ようこそ@Jom! – ventaquil

0

あなたは別で1つの部分文字列を置き換えるためにreplace()メソッドを使用することができます。この例では、先頭の "my"を ""(空の文字列)に置き換え、後ろの "はおいしい"と置き換えます。 ""(空文字列)を使用します。 "^"と "$"修飾子の詳細については、Regular Expressionsを参照してください。

var s = 'my salad and sandwiches are delicious.'; // example 
var y = s.replace(/^my /, '').replace(/are delicious\.$/, ''); 
alert(y); 
+0

あなたの答えを広げて、質問をしている人のために少しずつ分解してください。コードソリューションはそれほど役に立ちません – DiskJunky

0

これはなんですか?

map関数を使用すると、配列の要素をループして必要な値をすべて置き換えることができます。トリム機能は、文字列の両端に末尾に空白がないことを保証します。

var testcases = ['my cheesecakes are delicious.', 'cheesecakes', 
 
    'my salad and sandwiches are delicious.', 'salad and sandwiches', 
 
    'my tunas are delicious.', 'tunas' 
 
]; 
 

 
testcases = testcases.map(function(x) { 
 
    return x.replace("my", "").replace("are delicious.", "").trim(); 
 
}) 
 
console.log(testcases);
.as-console { 
 
    height: 100% 
 
} 
 

 
.as-console-wrapper { 
 
    max-height: 100% !important; 
 
    top: 0; 
 
}

0

あなたは1つが代わるとの不要な部分を置き換えることができます。内側部分が一致する

var strings = ['my cheesecakes are delicious.', 'my salad and sandwiches are delicious.', 'my tunas are delicious.', 'foo']; 
 

 
console.log(strings.map(function (s) { 
 
    return s.replace(/my\s+|\s+are\sdelicious\./g, ''); 
 
}));

提案。

var strings = ['my cheesecakes are delicious.', 'my salad and sandwiches are delicious.', 'my tunas are delicious.', 'foo']; 
 

 
console.log(strings.map(function (s) { 
 
    return (s.match(/^my (.*) are delicious\.$/) || [,''])[1]; 
 
}));

関連する問題