Remove all dots except the first one from a string

前端 未结 12 2597
栀梦
栀梦 2020-12-15 06:34

Given a string

\'1.2.3.4.5\'

I would like to get this output

\'1.2345\'

(In case there are no dots in the

12条回答
  •  一生所求
    2020-12-15 07:03

    Trying to keep this as short and readable as possible, you can do the following:

    JavaScript

    var match = string.match(/^[^.]*\.|[^.]+/g);
    string = match ? match.join('') : string;
    

    Requires a second line of code, because if match() returns null, we'll get an exception trying to call join() on null. (Improvements welcome.)

    Objective-J / Cappuccino (superset of JavaScript)

    string = [string.match(/^[^.]*\.|[^.]+/g) componentsJoinedByString:''] || string;
    

    Can do it in a single line, because its selectors (such as componentsJoinedByString:) simply return null when sent to a null value, rather than throwing an exception.

    As for the regular expression, I'm matching all substrings consisting of either (a) the start of the string + any potential number of non-dot characters + a dot, or (b) any existing number of non-dot characters. When we join all matches back together, we have essentially removed any dot except the first.

提交回复
热议问题