开发者

RegExp Weirdness in JavaScript

I have a variable string in my JavaScript code containing a comma delimited list of words and or phrases, for example:

String 1 : “abc, def hij, klm”

String 2 : “abc, def”

I w开发者_JS百科ant to insert the word ‘and’ after the last comma in the string to get

String 1 : “abc, def hij, and klm”

String 2 : “abc, and def”

I put together the following code:

// replace the last comma in the list with  ", and"  
var regEx1 = new RegExp(",(?=[A-z ]*$)" )      
var commaDelimList = commaDelimList.replace(regEx1, ", and ");

The problem is that it does not work if the comma delimited string has only two items separated by one comma.

So the results of the above example are

String 1 : ”abc, def hij, and klm”

String 2 : “abc, def”

Why is the RegExp not working and what can I use to get the result I want?


Not sure a regex was the right way to go there...

Why not use LastIndexOf and replace that with your string?


Since this is a relatively straight forward task, a little string manipulation may be beneficial - you'll realize better performance too.

var str = 'abc, def, hij, klm',
    index = str.lastIndexOf(','),
    JOINER = ', and';

//'abc, def, hij, and klm'
str.slice(0, index) + JOINER + str.slice(index+1);


Haven't tried you one but this works

'abc, def'.replace( /,(?=[A-z ]*$)/, ", and" )
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜