2016-01-13 62 views
0

好吧,所以我試圖創建一個JavaScript函數來替換字符串中的特定字符。我的意思是,讓我們說,逐個字符地搜索一個字符串作爲一個字母,如果它匹配,用另一個字符替換它。例如,將「a」替換爲「x」:Hello, how are you?變成Hello, how xre you?並且Greetings and salutations變成Greetings and sxlutations替換字符串中的特定字符 - JavaScript

+1

見https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – guest271314

+1

'String.prototype.replace'正是這樣做的。例如:('halp me plase')。replace('a','x')==='hxlp me plase'' – PitaJ

+0

請參閱http://www.w3schools.com/jsref/jsref_replace.asp使用javascript或http://www.jquerybyexample.net/2012/07/jquery-replace-strings.html與Jquery –

回答

0

由於String.replace()似乎不滿足OP的願望,這裏是一個完整的功能來做OP的要求。

function rep(s,from,to){ 
    var out = ""; 
    // Most checks&balances ommited, here's one example 
    if(to.length != 1 || from.length != 1) 
    return NULL; 

    for(var i = 0;i < s.length; i++){ 
    if(s.charAt(i) === from){ 
     out += to; 
    } else { 
     out += s.charAt(i); 
    } 
    } 
    return out; 
} 

rep("qwertz","r","X") 
0

var s1 = document.getElementById('s1').innerHTML; 
 
var s2 = s1.replace('a', 'x'); 
 
document.getElementById('s2').innerHTML = s2;
<h1>Starting string:</h1> 
 
<p id="s1">Hello, how are you?</p> 
 

 
<h1>Resulting string:</h1> 
 
<p id="s2"></p>

0

下面是一個簡單實用的功能,將與更換字符/字符串替換某個字符串海峽所有字符。

function replace(str, old, replacement) { 
     var newStr = new String(); 
     var len = str.length; 
     for (var i = 0; i < len; i++) { 
      if (str[i] == old) 
       newStr = newStr.concat(replacement); 
      else 
       newStr = newStr.concat(str[i]);     
     } 
     return str; 
    }