2016-03-25 40 views
1

我查了這個問題,但對編碼是新的,所以我不能很好地與其他答案聯繫起來。如何替換除第一個以外的多個字符?

給定一個字符串s,返回一個字符串
其中的第一個字符的所有實例都 被改爲「*」,但不改變
的第一個字符本身。 例如'babble'yield'ba ** le' 假設字符串長度爲1或更長。 提示:s.replace(stra,strb)返回字符串s 的一個版本,其中stra的所有實例都被strb替換。

這就是我所擁有的,但這並不代替除第一個以外的每個字符,它只是替換下一個字符。

function fixStart(s) 
    { 
    var c = s.charAt(0); 
    return c + s.slice(1).replace(c, '*'); 
    } 

回答

0

要更換所有出現不只是第一個,你可以使用一個RegExp

function fixStart(s) { 
    var c = s.charAt(0); 
    return c + s.slice(1).replace(new RegExp(c, 'g'), '*'); 
} 

例如如果c值是「B」,然後new RegExp(c, 'g')相當於/b/g

這將適用於簡單的字符串,如你的例子中的「babble」。如果字符串可能以正則表達式中的特殊符號開頭,例如'。',那麼您需要將其轉義,如@Oriol在評論中指出的那樣。看看this other answer是如何完成的。

+0

Thanks @Oriol,good point,added to my post。 – janos

0
function fixStart(s) { 
    var c = s.charAt(0); 
    var outputStr = ''; 
    // literate through the entire string pushing letters into a new string unless it is the first letter 
    for (var i = 0; i < s.length; i++) { 
     // if the letter is the first letter AND we are not checking the first letter 
     if (s[i] === c && i !== 0) outputStr += '*' 
     else outputStr += s[i] 
    } 
    return outputStr; 
    } 

    console.log(fixStart('hellohahaha')) 
相關問題