简体   繁体   中英

How to I Add In Degree Symbols to Temperatures in a Javascript String?

I have a string that was returned from an API, and I want to add in degree symbols from the temperatures that are included ("Tomorrow will be a high of 89F" → "Tomorrow will be a high of 89°F"). What would the Regex look like for my variable named forecastString ?

This replace will work:

forecastString = forecastString.replace(/[0-9]{1,3}F/g, function addDegreeSymbol(x){return x.replace("F", "°F");});
forecastString = forecastString.replace(/[0-9]{1,3}C/g, function addDegreeSymbol(x){return x.replace("C", "°C");});

The Regex finds any numbers of 1-3 digits followed immediately by an F/C, and replaces the F/C with °F/°C

Why not

forecastString.replace(/\b(\d{1,3})(?=[FC]\b)/, "$1°");

? Are you sure about case insensitivity?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM