admin管理员组文章数量:1399119
I have a string that will sometimes include a hyphen (-) and sometimes won't. When the string contains a hyphen, I want to remove or hide the hyphen and any text that es after it.
For instance, 'john' would be rendered 'john'. And 'john-hops-over-the-candlestick' would also be rendered 'john'.
I have a string that will sometimes include a hyphen (-) and sometimes won't. When the string contains a hyphen, I want to remove or hide the hyphen and any text that es after it.
For instance, 'john' would be rendered 'john'. And 'john-hops-over-the-candlestick' would also be rendered 'john'.
Share Improve this question asked Nov 7, 2014 at 3:00 Tony BrasunasTony Brasunas 4,6213 gold badges46 silver badges60 bronze badges 3- Wow, several good answers have e in immediately. Not sure how to choose the best, but I'll choose in a minute here. I've also realized I need to loop through the elements with jquery and then run this routine on each via jquery's text() method. – Tony Brasunas Commented Nov 7, 2014 at 3:31
-
OK, many of the answers could've worked, and I went with the regex in my jquery, as follows:
$( "span.first-name").each(function() { $(this).text($(this).text().replace(/-.*$/, '')); });
– Tony Brasunas Commented Nov 7, 2014 at 3:44 - 2 I like these types of questions, where the problem isn't necessarily difficult to solve, but you get a lot of interesting different approaches that acplish the same thing. (Well, the answers that work correctly, anyway.) – Troy Gizzi Commented Nov 7, 2014 at 3:57
4 Answers
Reset to default 3You can use a simple regular expression replacement
myString.replace(/-.*$/, '')
For example
var myString = 'john';
alert('"' + myString + '" bees "' + myString.replace(/-.*$/, '') + '"');
myString = 'john-hops-over-the-candlestick';
alert('"' + myString + '" bees "' + myString.replace(/-.*$/, '') + '"');
The following truncateAt
function should do what you want.
var string1 = 'john';
var string2 = 'john-hops-over-the-candlestick';
var string3 = 'john hops over the candlestick';
function truncateAt(str, char) {
var idx = str.indexOf(char);
return idx === -1 ? str : str.substr(0, idx);
}
console.log(truncateAt(string1, '-'));
console.log(truncateAt(string2, '-'));
console.log(truncateAt(string3, '-'));
Try this:
function breakAt(str, at){
return str.split(at)[0];
}
console.log(breakAt('john-hops-over-the-candlestick', '-'));
console.log(breakAt('john-hops-over-the-candlestick', 'john'));
you can use split();
var str = 'john-sample';
var substr = str.split('-');
fname = substr[0];
alert(fname);
本文标签:
版权声明:本文标题:How to hide the end of a string after a certain character, with javascript or jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744213170a2595516.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论