1

I am getting stuck in JavaScript trying to modify my strings.

I am using Met-Office APT to extract weather forecast strings. Problem is temperature in them doesn't have a degree symbol, i.e.:

"Maximum Temperature 15C."

How to search within a random string for a temperature value and either replace "C" with "degrees" or insert degree symbol in-between the value and the C?

This might be really simple but I am just a noob.

My goal is to push modified string through TTS service.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Sloma
  • 11
  • 1
  • https://stackoverflow.com/questions/31669536/how-to-put-a-degree-symbol-in-an-html-input-field-through-javascript – James Sep 27 '22 at 16:57
  • If you want the actual character in your string and not a character code for HTML to render, what I've done in the past is I've copied the symbol from somewhere else on the web, then pasted it into my code and it'll put it in the string for you. `°` – mhodges Sep 27 '22 at 16:59
  • Does this answer your question? [Insert a string at a specific index](https://stackoverflow.com/questions/4313841/insert-a-string-at-a-specific-index) – Heretic Monkey Sep 27 '22 at 17:02

2 Answers2

3

If you have it as a string, do a string replacement with a regular expression that matches your pattern of one or more numbers followed by C

let yourString = "Maximum Temperature 15C."
yourString = yourString.replace(/(\d+)([CF])/,'$1°$2');
console.log(yourString);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • If having a C or F in the middle of the string is an issue, you can alternatively match on the `C.` at the end of the string, like so: `"Maximum Temperature 15C.".replace(/C.$/, '°C.')` – mhodges Sep 27 '22 at 17:05
0

You can try this imperative solution

const addTempratureUnit =(temperatureDetails,unit,symbol)=>{
    let outputTempratureDetails=""
    for (let i=0;i<temperatureDetails.length;i++){
   
    if(temperatureDetails[i]===unit&&(temperatureDetails[i-1]!==""&&!isNaN(temperatureDetails[i-1]))){
       outputTempratureDetails+=symbol
    }else{
      outputTempratureDetails+=temperatureDetails[i]
    }
}
  return outputTempratureDetails  


    
}
const temperatureDetails="Maximum Temperature 15C."
const modifiedTemperatureDetails=addTempratureUnit(temperatureDetails,"C","°C")
console.log(modifiedTemperatureDetails)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 30 '22 at 18:06