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
Add a ment  | 

4 Answers 4

Reset to default 3

You 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);

本文标签: