简体   繁体   English

使用regExp在两个特定字符之间添加正斜杠

[英]Add a forward slash between two specific characters with regExp

I know how to delete/replace elements in a string with regExp. 我知道如何使用regExp删除/替换字符串中的元素。 But is it possible to add a character between two specific characters using regExp ? 但是可以使用regExp在两个特定字符之间添加一个字符吗?

I'm already using this regExp to match object properties from the value of a user input : new RegExp("^" + o.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, "\\\\$&") + "$", "i"); 我已经在使用此regExp从用户输入的值中匹配对象属性: 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 : 除了在两个特定字符之间添加正斜杠外,此行可以满足我的需要:每当'k'后跟'm'时,我都需要在它们之间添加正斜杠以匹配此对象的属性:

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 . 因此,如果我的输入值为'km / h''kmh' ,则两个字符串都应与obj中的'km / h'相等。 Is it possible to do it using regExp ? 有可能使用regExp吗?

Here is where I'm stuck : https://jsfiddle.net/Hal_9100/p0Lwg85w/1/ 这是我卡住的地方: 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 : 仍在寻找更优雅的方法或在我现有的regExp中实现该方法的简单方法:

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

Any suggestion would be much appreciated 任何建议将不胜感激

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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