2017-10-11 267 views
0

的单个或多个出现我已经写了下面的功能转换的空间连字符或反向正则表达式替换连字符

  1. 空间连字符str.trim().replace(/\s+/g, '-')
  2. 连字符与空间str.replace(/\-/g,' ')

但现在我我试图用双连字符替换单个连字符,我不能使用点1函数,因为它转换单个/多个事件而不是单个事件。

有什么办法来写正则表达式里面做3次手术单式

  1. 转换带连字符下划线replace(/\//g, '_')
  2. 转换空间斜杠
  3. 转换一个连字符与多个连字符

eg 正则表达式1变化

"Name/Er-Gourav Mukhija" into "Name_Er--Gourav-Mukhija" 

正则表达式2做它的倒过来。

回答

0

这是不可能写一个正则表达式做条件替换(即a-> b,c-> d)。我会尝试创建两个语句来替换“” - >“ - ”和“/” - >“_”。

您可以使用您的现有代码进行这两种操作。我建议将来使用this site来构建和测试正则表达式。

+0

Regexr与javascript regexp版本存在一些问题。更好地使用[regex101](https://regex101.com) – lumio

4

您可以使用回调函数而不是替换字符串。这样您就可以一次指定并替换所有字符。

const input = 'Name/Er-Gourav Mukhija'; 
 
const translate = { 
 
    '/': '_', 
 
    '-': '--', 
 
    ' ': '-', 
 
}; 
 
const reverse = { 
 
    '_': '/', 
 
    '--': '-', 
 
    '-': ' ', 
 
}; 
 

 
// This is just a helper function that takes 
 
// the input string, the regex and the object 
 
// to translate snippets. 
 
function replaceWithObject(input, regex, translationObj) { 
 
    return input.replace(regex, function(match) { 
 
    return translationObj[ match ] ? translationObj[ match ] : match; 
 
    }); 
 
} 
 

 
function convertString(input) { 
 
    // Search for /, - and spaces 
 
    return replaceWithObject(input, /(\/|\-|\s)/g, translate); 
 
} 
 

 
function reverseConvertedString(input) { 
 
    // Search for _, -- and - (the order here is very important!) 
 
    return replaceWithObject(input, /(_|\-\-|\-)/g, reverse); 
 
} 
 

 
const result = convertString(input); 
 
console.log(result); 
 
console.log(reverseConvertedString(result));

0

考虑var str = "Name/Er-Gourav Mukhija"

  1. 要转换向前下划线斜线,你所说的采用replace(/\//g, '_')
  2. 要转换的空间与一个连字符,使用replace(/\s+/g, '-')
  3. 要转换单连字符双连字符,使用replace(/\-/g, '--')

所有这3个可组合成:

str.replace(/\//g, '_').replace(/\s+/g, '-').replace(/\-/g, '--')

0

您应该使用一个循环来一下子做到:

str = str.split(""); 
var newStr = ""; 
str.forEach(function (curChar) { 
    switch(curChar) { 
    case " ": 
     newStr += "-"; 
     break; 
    case "/": 
     newStr += "_"; 
     break; 
    case "-": 
     newStr += "--"; 
     break; 
    default: 
     newStr += curChar; 
    } 
}); 
str = newStr; 

随意把它变成如果一个函数你喜欢。我也没有做相反的事情,但是你只需要在switch()语句中用赋值字符串替换赋值字符串即可。

无法用正则表达式来完成这一切,因为无论您如何编写它,后面的正则表达式都会在至少一个案例中覆盖您的第一个正则表达式。