我有一個字串
var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"
現在我想在每個子字串周圍加上雙引號
即必需的字串
var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""
這有可能在javascript中實作這樣的事情嗎?
uj5u.com熱心網友回復:
如果您打算將包含用逗號分隔的“單詞”的字串轉換為用雙引號括起來的相同“單詞”的字串,例如,您可以使用分割原始字串,.split(',')然后回圈遍歷結果陣列以組成包含每個字串的輸出字串引號之間的專案:
function transform(value){
const words = value.split(',');
let output = '';
for(word of words){
output = `"${word.trim()}", `;
}
output = output.slice(0, -2);
return output;
}
const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);
這是真的,除非你只是想定義一個包含需要轉義的字符的字串文字。在這種情況下,您有幾種方法,例如對字串文字或反引號使用單引號(但這更適合模板字串)。\"或者,如果您用雙引號將文字括起來,則只需轉義您的值。
uj5u.com熱心網友回復:
您可以使用反引號``
var st = `"asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104"`
uj5u.com熱心網友回復:
You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:
const result = myString
.split(', ')
.map(word => `"${word}"`)
.join(', ')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505608.html
標籤:javascript 细绳 格式化
上一篇:在兩個字符之間拆分字串?
下一篇:如何在范圍外共享動態加載的類
