2017-10-11 124 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()語句中用賦值字符串替換賦值字符串即可。

無法用正則表達式來完成這一切,因爲無論您如何編寫它,後面的正則表達式都會在至少一個案例中覆蓋您的第一個正則表達式。