I have a string and I want the number groups inside be reversed, for example "this is number 123456 and the reverse is 654321" be changed to "this is number 654321 and the reverse is 123456" . how can I achieve that?
As I searched through net , I finally got to this solution:
function reverseNumberInString(str){
let numbers = str.match(/\d+/g) || [];
for(let i = 0 ; i < numbers.length ; i++){
let x = numbers[i].toString().split("").reverse().join("");
let s = str
str = s.slice(0,str.search(numbers[i])) + x + s.slice(str.search(numbers[i])+numbers[i].length)
}
return str
}
Might Be Interesting:
The whole problem started with thermal pos printer. I had to send a string of hex codes to it for printing , but in my language (persian/farsi) it would print in reverse , so I had to reverse the hex string. but then numbers would be reverse (and of course English words!!) so I reversed the numbers (and for English letters just change str.match(/\d+/g) to str.match(/\w+/g)) in side the reversed string!
Updated:
I also found out that decimal number have problems too. so I changed the regex part to str.match(/[a-zA-Z0-9.،,\/]+/g)