Pregunta

Lone developer here. Looking for some ideas how I can detect numbers in a string and reverse the characters of said numbers. For example given the string:

'Lorem ipsum dolor 345 sit $4.50 amet,78% consectetur 45.60%adipisicing elit'  

The resulting string would be:

'Lorem ipsum dolor 543 sit 05.4$ amet,%87 consectetur %06.54adipisicing elit'  

The trick is identifying the whole number segment which may include currency symbol, percentage symbol, period or comma decimal separators, thousand separators. I'd like to be able to reverse the sub section of a string relating to, and being a number.

Ideas?

¿Fue útil?

Solución

This is probably a good job for a regular expression:

var result = input.replace(/\$?[0-9]+(\.[0-9]+)?%?/g,
                           function(s) { return s.split('').reverse().join(''); });

Demo: http://jsfiddle.net/6A3Nn/2/

Otros consejos

str = str.replace(/[0-9.$%]+/g, function(x) {
    return x.split('').reverse().join('')
});

FIDDLE

A bit crude but should work.

function reverseNumInStr(str){
  var wordArray = str.split(' ');

  var newList = [];
  wordArray.forEach(function(word){
    var newWord = word.replace("$","").replace(".","").replace("%","").replace(",","");

    var num = parseFloat(newWord);

    if(!isNaN(num)){
      newList.push(word);
    }else{
      newList.push(reverseStr(word));
    }

  });

  return newList.join(" ");
}

function reverseStr(s){
    return s.split("").reverse().join("");
}
var output = input.replace(/[0-9.$%]+/g, function(oneway) {
    return oneway.split("").reverse().join("");
  });

Plunker

Given below are some useful references

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top