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

S16*_*S16 12 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>
Run Code Online (Sandbox Code Playgroud)

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

Izk*_*ata 27

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

text = 'Something -that - has- dashes - World';
parts = text.split('-');
loc = parts.pop();
new_text = parts.join('-');
Run Code Online (Sandbox Code Playgroud)

所以,

loc == ' World';
new_text == 'Something -that - has- dashes ';
Run Code Online (Sandbox Code Playgroud)

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


Wil*_*ill 13

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

"String - Location".split('-').pop().trim(); // "Location"
Run Code Online (Sandbox Code Playgroud)

所以使用jQuery就可以了

$('.v2_review-text').html().split('-').pop().trim(); // "United States"
Run Code Online (Sandbox Code Playgroud)

或者使用香草JS

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


fuj*_*ujy 6

试试这个

str2 = str.substring(str.lastIndexOf("-"))
Run Code Online (Sandbox Code Playgroud)