How to replace all BUT the first occurrence of a pattern in string

后端 未结 6 729
余生分开走
余生分开走 2020-12-03 07:04

quick question: my pattern is an svg string and it looks like l 5 0 l 0 10 l -5 0 l 0 -10 To do some unittest comparison against a reference I need to ditch all

6条回答
  •  借酒劲吻你
    2020-12-03 07:33

    It's not the prettiest solution, but you could replace the first occurrence with something arbitrary (like a placeholder) and chain replacements to fulfill the rest of the logic:

    '-98324792u4234jkdfhk.sj.dh-f01' // construct valid float
        .replace(/[^\d\.-]/g, '') // first, remove all characters that aren't common
        .replace(/(?!^)-/g, '') // replace negative characters that aren't in beginning
        .replace('.', '%FD%') // replace first occurrence of decimal point (placeholder)
        .replace(/\./g, '') // now replace all but first occurrence (refer to above)
        .replace(/%FD%(0+)?$/, '') // remove placeholder if not necessary at end of string
        .replace('%FD%', '.') // otherwise, replace placeholder with period
    

    Produces:

    -983247924234.01

    This merely expands on the accepted answer for anyone looking for an example that can't depend on the first match/occurrence being the first character in the string.

提交回复
热议问题