获取字符串中最后一个' - '后面的所有字符

时间:2013-09-05 21:38:10

标签: javascript jquery

我正在一些非常严格的打包端限制中工作,并且有一个客户端在他的请求中坚持不懈,所以我不得不在.js中做一些我宁愿做的事情。

无论如何,这里有。

我有客户评论。在那些评论结束时,我有' - 美国'或' - 澳大利亚'。基本上,在每次审核结束时我都会' - [位置]'。我需要从审阅文本中提取该字符串,然后将其插入范围。我正在使用jQuery,所以我想坚持下去。

我已经整理了如何浏览每个评论并将其插入到我需要的地方,但我还没想出如何从每个评论中获取该文本字符串,然后从每个评论中删除它。这就是我真正可以帮助的地方。

示例文字:

<div class="v2_review-content">
    <h4>These earplugs are unbelievable!</h4>
    <p class="v2_review-text">These are the only earplugs I have ever used that completely block out annoying sounds. I use them at night due to the fact I am an extremely light sleeper and the slightest noise will wake me up. These actually stick to the ear in an airtight suction and do not come out at all until I pull them off in the morning. These are as close to the perfect earplug as you can get! - United States</p>
    <p class="v2_review-author">Jimmy, March 06, 2013</p>
</div>

如果有帮助,我也可以使用underscore.js。

6 个答案:

答案 0 :(得分:24)

实际的字符串操作不需要jQuery - 有点笨重,但很容易理解:

text = 'Something -that - has- dashes - World';
parts = text.split('-');
loc = parts.pop();
new_text = parts.join('-');

所以,

loc == ' World';
new_text == 'Something -that - has- dashes ';

可以修剪或忽略空格(因为在HTML中通常无关紧要)。

答案 1 :(得分:11)

首先将搅拌分开' - ',这将在破折号之间提供一系列字符串。然后将它作为一个堆栈使用并弹出最后一个元素并调用trim来删除任何一个讨厌的空格(除非你喜欢你的空格当然)。

"String - Location".split('-').pop().trim(); // "Location"

所以使用jQuery就是

$('.v2_review-text').html().split('-').pop().trim(); // "United States"

或使用vanilla JS

var text = document.getElementsByClassName('v2_review-text')[0].innerHTML;
text.split('-').pop().trim(); // "United States"

答案 2 :(得分:5)

尝试这样的事情

str2 = str.substring(str.lastIndexOf("-"))

答案 3 :(得分:3)

最简单的方法可能是使用jQuery来获取元素,使用本机JavaScript来获取字符串:

var fullReview = $('.v2_review-text').text(); //assumes only one review exists, adjust for your use.
var country = fullReview.substring(fullReview.lastIndexOf(' - ') + 1); //TODO correct for -1 if ' - ' not found.

这只是概念的证明;其余应该相对容易弄明白。在您学习的过程中要注意的一些事项:jQuery each

答案 4 :(得分:2)

var val = $('.v2_review-text').text();
var city_array = val.split('-');
var city = city_array[city_array.length - 1];

希望我能帮助你了。

答案 5 :(得分:1)

var completeText = $('.v2_review-text')[0].value;
var country = completeText.substr(completeText.lastIndexOf('-'), completeText.lenght - 1);
相关问题