开发者

Regular Expression in JS

How do you trim all of the text after a comma using JS?

I ha开发者_StackOverflowve: string = Doyletown, PA

I want: string = Doyletown


var str = 'Doyletown, PA';
var newstr=str.substring(0,str.indexOf(',')) || str;

I added the || str to handle a scenario where the string has no comma


How about a split:

var string = 'Doyletown, PA';
var parts = string.split(',');
if (parts.length > 0) {
    var result = parts[0];
    alert(result); // alerts Doyletown
}


using regular expression it will be like:

var str = "Doyletown, PA"
var matches = str.match(/^([^,]+)/);
alert(matches[1]);

jsFiddle

btw: I would also prefer .split() method


Or more generally (getting all the words in a comma separated list):

//Gets all the words/sentences in a comma separated list and trims these words/sentences to get rid of outer spaces and other whitespace.
var matches = str.match(/[^,\s]+[^,]*[^,\s]+/g);


Try this:

str = str.replace(/,.*/, '');

Or play with this jsfiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜