我正在尝试使用replace(searchvalue, newvalue);
和用户输入作为搜索字词。
一个例子是replace(input,"example text");
但我想要的是能够拥有搜索词,但不是替换搜索词,而是替换它前面的空格。
实施例。是句子:"Hi, I am using js to create this!"
和用户输入"js"
replace(input, "html and ");
但不是替换"js"
,而是替换前面的空格。因此输出句子将是:
"Hi, I am using html and js to create this!"
无论如何都要替换吗?
答案 0 :(得分:2)
您可以使用函数来处理string.replace
中的替换。
var newString = 'Hi, I am using js to create this!'.replace('js', function(match) {
return 'html and ' + match;
});
console.log(newString); // ... using html and js ...
在上面的示例中,我预先添加" html和"到变量匹配(其值为" js")。使用正则表达式而不是字符串来查找匹配时有很大的灵活性。
<强> MDN 强>