2017-10-15 90 views
2

我是新來的Javascript。我有點困惑,我怎麼能拉一個字符串內的特定字符串。爲了使它更清晰,我想在下面的示例中刪除myare delicious.,並且只返回兩者之間的文本。儘可能長,不需要jQuery。JavaScript:拉一個字符串內的特定字符串

'my cheesecakes are delicious.' 'cheesecakes'

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

'my tunas are delicious.' 'tunas'

+2

歡迎SO。請包括嘗試解決方案,爲什麼他們不工作,以及預期的結果。這真的可以幫助我們找出你的代碼的問題。謝謝! –

回答

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

您可以使用replace()方法與另一個替換一個字符串。在這個例子中,我首先用「」(空串)替換了前導「我的」,尾隨的「很好吃」。用「」(空字符串)。有關「^」和「$」修飾符的更多信息,請查看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

你可以更換不需要的部分,請換一個。

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]; 
 
}));

相關問題