如何在angularjs中拆分字符串?

PSw*_* AC 1 javascript

我使用j时有一个问题.我有一个字符串=> "c:0.1|d:0.2",我需要像这样输出=>c:10%?d:20%

Pra*_*lan 6

使用String#split,Array#mapArray#join方法.

var str = "c:0.1|d:0.2";

console.log(
  str
  // split string by delimitter `|`
  .split('|')
  // iterate and generate result string
  .map(function(v) {
    // split string based on `:`
    var s = v.split(':')
      // generate the string
    return s[0] + ':' + (Number(s[1]) * 100) + "%"
  })
  // join them back to the format
  .join()
)
Run Code Online (Sandbox Code Playgroud)


您还可以使用String#replace方法与捕获组正则表达式和一个回调函数.

var str = "c:0.1|d:0.2";

console.log(
  str.replace(/\b([a-z]:)(0\.\d{1,2})(\|?)/gi, function(m, m1, m2, m3) {
    return m1 +
      (Number(m2) * 100) + // calculate the percentage value
      (m3 ? "%," : "%") // based on the captured value put `,`
  })
)
Run Code Online (Sandbox Code Playgroud)

正则表达式在这里解释.