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 comes after it.
For instance, 'john' would be rendered 'john'. And 'john-hops-over-the-candlestick' would also be rendered 'john'.
You can use a simple regular expression replacement
myString.replace(/-.*$/, '')
For example
var myString = 'john';
alert('"' + myString + '" becomes "' + myString.replace(/-.*$/, '') + '"');
myString = 'john-hops-over-the-candlestick';
alert('"' + myString + '" becomes "' + myString.replace(/-.*$/, '') + '"');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With