2017-10-15 46 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]; 
 
}));

相关问题