我有以下JavaScript變量。在字符串變量中插入幾個字符之前(javascript)
var data = "ashley, andy, juana"
我希望上述數據看起來像這樣。
var data = "Sports_ashley, Sports_andy, Sports_juana"
它應該是動態的本質。此變量中可以包含任意數量的逗號。
有人可以讓我一個簡單的方法來實現這一點,請。
我有以下JavaScript變量。在字符串變量中插入幾個字符之前(javascript)
var data = "ashley, andy, juana"
我希望上述數據看起來像這樣。
var data = "Sports_ashley, Sports_andy, Sports_juana"
它應該是動態的本質。此變量中可以包含任意數量的逗號。
有人可以讓我一個簡單的方法來實現這一點,請。
可能矯枉過正,但這裏是一個通用的解決方案
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"));
編輯:與OP
的新版本更新的使用正則表達式使用String#replace()
var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);
這ISN更換
,
的所有匹配或字符串的開頭是一個讓人們爲你做功課的網站。如果你已經做出了嘗試,然後顯示代碼,否則問一個更具體的問題,而不是「有人可以幫我嗎?」 – Justin