Skip to content Skip to sidebar Skip to footer

Jquery Remove Everything After And Including Certain Character

I have a location - Pearl River, NY (10965) that I want displayed as Pearl River, NY (so it must delete (10965) -- including the space before ( -- I'm not looking to make a big dea

Solution 1:

location_string = location_string.replace(/ \([^)]*\)/, '');

On a side note, please stop thinking that jQuery is necessary for anything at all, especially not a string manipulation task like this. It really isn't, and jQuery is overhyped.

Solution 2:

I'm not sure how you're given "Peal River NY..." (variable? innerHTML?), but you need to use a regular expression to match the (numbers), and the replace method to substitute the match for nothing "".

"Peal River, NY (10965)".replace(/ \([0-9]+\)/, "");

This doesn't use jQuery!

See the String.replace method.

As mentioned by @James in the comments, this snippet will leave "Peal River, NY ()" as "Peal River, NY ()", rather than removing the brackets. If this is a case you need to consider, change the + to *:

"Peal River, NY (10965)".replace(/ \([0-9]*\)/, "");

Solution 3:

Use a regex:

var s = "Pearl River, NY (10965)";
alert(s.replace(/ \([\d]*\)/,''));

See it at this JSFiddle

Of course, here I am assuming you'll be wanting to replace only numbers in the brackets. For letter and underscore, use \w in place of \d

You might also want to make it a requirement that the item occurs at the end. In which case, the following will suffice:

alert(s.replace(/ \([\d]*\)$/,''));

You'll note that none of the above references jQuery. This is something that can be achieved with pure JavaScript.

Post a Comment for "Jquery Remove Everything After And Including Certain Character"