1

Ihave a problem when I use js.I have a string=>"c:0.1|d:0.2" and I need output like this=> c:10%,d:20%

0

2 Answers 2

6

Use String#split, Array#map and Array#join methods.

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

console.log(
  str
  // split string by delimiter `|`
  .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()
)


You can also use String#replace method with capturing group regex and a callback function.

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 `,`
  })
)

Regex explanation here.

Sign up to request clarification or add additional context in comments.

Comments

1

It's not angular issue, you can use simple logic, use substring take value after the : and multiply by 100 to get the value as 10 or respective.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.