开发者

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 s开发者_运维问答pace before ( -- I'm not looking to make a big deal of this and do anything server side. jQuery would work fine. I know this is probably simple as hell, I just don't use JS much.

Thanks!


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.


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]*\)/, "");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜