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



我正在一些非常严格的包端限制下工作,并且有一个客户对他的要求毫不留情,所以我被迫在.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>

我也有下划线.js如果有帮助的话。

实际的字符串操作不需要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中通常无关紧要)。

首先在"-"上拆分马镫,这将在破折号之间为您提供一个字符串数组。 然后将其用作堆栈并弹出最后一个元素并调用 trim 以删除任何讨厌的空格(当然,除非您喜欢您的空格)。

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

所以使用jQuery将是

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

或使用香草 JS

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

试试这样的事情

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

最简单的方法可能是使用 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

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

希望我帮了你哥们。

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

最新更新