2016-08-08 188 views
0

我有以下JavaScript變量。在字符串變量中插入幾個字符之前(javascript)

var data = "ashley, andy, juana" 

我希望上述數據看起來像這樣。

var data = "Sports_ashley, Sports_andy, Sports_juana" 

它應該是動態的本質。此變量中可以包含任意數量的逗號。

有人可以讓我一個簡單的方法來實現這一點,請。

+1

這ISN更換,的所有匹配或字符串的開頭是一個讓人們爲你做功課的網站。如果你已經做出了嘗試,然後顯示代碼,否則問一個更具體的問題,而不是「有人可以幫我嗎?」 – Justin

回答

2

使用.replace應該在每個逗號前添加運動項。下面我列舉了一個例子。

var data = data.replace(/,/g , ", Sports_"); 

在使用正則表達式與g標誌將替換所有逗號與Sports,,而不只是第一次出現該例子。

然後在最後,你應該能夠像這樣追加Sports到最後。

data = "Sports_" + data; 
+0

請不要使用W3School作爲可靠的參考。 – 4castle

+0

@ 4castle任何原因? –

+0

這往往是錯誤的,並沒有詳細說明。 – 4castle

2

可能矯枉過正,但這裏是一個通用的解決方案

function sportify(data) { 
 
    return data 
 
    .split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces 
 
    .map(function(name) { return "Sports_" + name }) //each name chunk gets "Sport_" prepended to the end 
 
    .join(", "); //combine them back together 
 
    } 
 

 
console.log(sportify("ashley, andy, juana")); 
 
console.log(sportify("ashley , andy,  juana"));

String.replace()

Array.map()

Array.join()

編輯:與OP

2

的新版本更新的使用正則表達式使用String#replace()

var input = "ashley, andy, juana" 
 
var output = input.replace(/^|,\s*/g, "$&Sports_"); 
 
console.log(output);

+0

@ 4castle-謝謝你。我稍微更新了我的問題。你可以pelase看看,讓我知道如何得到那 – Patrick

+1

@Patrick現在更新。謝謝你讓我知道。 – 4castle

+0

@ 4castle-我得到了Sports_ashley,andy,juana作爲你的代碼輸出。 – Patrick

相關問題