Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide the end of a string after a certain character, with javascript or jquery

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'.

like image 242
Tony Brasunas Avatar asked Dec 31 '25 14:12

Tony Brasunas


1 Answers

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(/-.*$/, '') + '"');
                                                        
like image 62
Phil Avatar answered Jan 03 '26 04:01

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!