简体   繁体   中英

Add a forward slash between two specific characters with regExp

I know how to delete/replace elements in a string with regExp. But is it possible to add a character between two specific characters using regExp ?

I'm already using this regExp to match object properties from the value of a user input : new RegExp("^" + o.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, "\\\\$&") + "$", "i");

This line works just fine for my needs except for adding a forward slash between two specific characters : whenever 'k' is followed by 'm', I need to add a forward slash between them to match the properties of this object :

var obj = {
  'km/h': '1.079e+9',
  'km': 0,
  'm/s': '2,998e+8',
  'm': 0
}; 

So if my input value is 'km/h' or 'kmh' , both strings should equally match 'km/h' in obj . Is it possible to do it using regExp ?

Here is where I'm stuck : https://jsfiddle.net/Hal_9100/p0Lwg85w/1/

Thanks for you help

Answering my own question, this seems to be the way to go :

var str = "kmh";
var test = str.replace(/m\s?h/i, 'm/h');
console.log(test);

Still looking for a more elegant approach or simply a way to implement it in my existing regExp :

new RegExp("^" + o.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$", "i");

Any suggestion would be much appreciated

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