JavaScript:在字符串

时间:2017-10-15 17:04:07

标签: javascript

我是Javascript的新手。我对如何在字符串中拉出特定字符串感到有点困惑。为了更清楚,我想删除下面示例中的myare delicious.,只返回两者之间的文本。只要有可能,就不需要jQuery。

'my cheesecakes are delicious.' 'cheesecakes'

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

'my tunas are delicious.' 'tunas'

4 个答案:

答案 0 :(得分:0)

您可以使用replace()方法将一个子字符串替换为另一个子字符串。在这个例子中,我首先取代了领先的" my"用"" (空字符串)和尾随"很美味。"用"" (空字符串)。有关" ^"的更多信息和" $"修饰符,请查看Regular Expressions

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

答案 1 :(得分:0)

这样的东西?

您可以使用map函数循环遍历数组的元素并替换所有必需的值。 trim函数将确保字符串边缘没有尾随空格。



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




答案 2 :(得分: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];
}));

答案 3 :(得分:0)

您可以使用.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);