2016-06-10 78 views
0

我有这个默认字符串:{0} blah blah blah blah {1}其中{0}{1}将在文本框中加载时替换为值。默认字符串内容的更改

例:{0} = "CUP"{1} = "GIRLS",将显示在文本框中的字符串为"CUP blah blah blah blah GIRLS"

现在的问题是这样的:当用户编辑默认消息,并点击“保存”,我怎么更换修改后的消息中的{0} =“CUP”和{1} =“GIRLS”? (在消息变化可以发生在原始消息的以往一部分)

回答

1

使用String#replace()方法

console.log(
 
    '{0} blah blah blah blah {1}' 
 
    .replace(/\{0}/, 'CUP') 
 
    .replace(/\{1}/, 'GIRLS') 
 
)


或存储替换内容的阵列内,然后更换与匹配的内容(偶对象可以在这里使用)。

var rep = ['CUP', 'GIRLS']; 
 

 
console.log(
 
    '{0} blah blah blah blah {1}' 
 
    .replace(/\{(\d+)}/g, function(_, m1) { 
 
    return rep[m1]; 
 
    }) 
 
)


UPDATE: 有两个文本输入工作演示。

var div = document.getElementById('result'), 
 
    t1 = document.getElementById('text1'), 
 
    t2 = document.getElementById('text2'), 
 
    str = '{0} blah blah blah blah {1}'; 
 

 
function change() { 
 
    div.innerHTML = str 
 
    .replace(/\{0}/, t1.value) 
 
    .replace(/\{1}/, t2.value) 
 
}
<input type="text" oninput="change()" id="text1" /> 
 
<input type="text" oninput="change()" id="text2" /> 
 
<div id="result"></div>

+0

这个怎么样的场景(在保存之前):'foo foo foo CUP foo blah blah blah GIRLS'?我不认为它会满足它。 – Musikero31

+0

@ Musikero31你需要将原始文本存储在一个字符串变量中...... –

+0

为什么不使用'{\ d +}'而不是硬代码来期望0或1 - 那么函数可以用来替换任意数量的字符串。 – Alnitak

1

您可以调用自定义替换功能:

var replace = function(s,d) { 
    return s.replace(/\{(\d+)\}/g,function(m,k,v){ 
     return d[k]; 
    }); 
} 

var result = replace("{0} blah blah blah blah {1}", ["hello", "world"]); 
console.log(result); 

//Returns: hello blah blah blah blah world 

或者你可以将这个方法添加到字符串类(不推荐)

String.prototype.rplc = function(data) { 
     return this.replace(/\{(\d+)\}/g,function(m,k,v){ 
      return data[k]; 
     }); 
    } 

var result = "{0} blah blah blah blah {1}".rplc(["hello", "world"]); 
console.log(result);  

//Returns: hello blah blah blah blah world 
+0

不错的答案,很好的广义函数:) – Alnitak