嗨,我有一个简单的问题,如何替换字符串的一部分。假设我们有一个字符串:
"This is my string that I need to replace a part FROM to a part TO."
,我想将字符串的“ FROM” 部分中的所有值替换为“ TO” 部分,例如,将其替换为“ XXX”,因此字符串应看起来喜欢:
"This is my string that I need to replace a part FROM XXX TO."
如何在JS中进行 SIMPLY (某些命令需要使用数字/索引,而charAt很难定位)?当然,字符串会有所不同,但是某些部分是相同的,我需要将它们定位为目标,并用特定的唯一字符串(在此示例中为XXX)替换“中间件” 。
我的想法是将FROM替换为某些特定标记(!),将TO替换为某些特定标记(@)。用可以使用获取索引所需的charAt()的命令将字符串从一个特定标记(FROM-!)替换为其他特定标记(TO-@)...但是它必须是一种更简单,更优雅的方法这样做。
帮助新手!
答案 0 :(得分:5)
一个选择可能是使用正则表达式在捕获组FROM
中进行匹配,然后在第二组中捕获任何非贪婪(.*?)
字符,然后是断言(?=
来断言什么以下是TO
替换为第1组,后跟空格和XXX
$1 XXX
var str = "This is my string that I need to replace a part FROM to a part TO.";
console.log(str.replace(/(FROM)(.*?)(?= TO)/, '$1 XXX'));
答案 1 :(得分:2)
有几种方法可以做到这一点。
var str = "This is my string that I need to replace a part FROM to a part TO.";
var res = str.replace(/FROM(.*)TO/, "FROM XXX TO");
var posFrom = str.indexOf('FROM');
var posTo = str.indexOf('TO', posFrom);
if (posFrom !== -1 && posTo !== -1) {
var res = str.substring(0, posFrom) + 'FROM XXX TO' + str.substring(posTo + 2)
}
在两种方法中,您都必须确保字符串中没有与FROM和TO关键字混淆的其他单词。
答案 2 :(得分:0)
将String#replace与RegExp配合使用:
(FROM )
的开头.*?
( TO)
并使用special replacement patterns $1
和$2
:
const string = "This is my string that I need to replace a part FROM to a part TO.";
const pattern = /(FROM ).*?( TO)/;
const replaced = string.replace(pattern, '$1XXX$2');
console.log(replaced);
或.replace()
中的replacement function:
const string = "This is my string that I need to replace a part FROM to a part TO.";
const pattern = /(FROM ).*?( TO)/;
const replaced = string.replace(pattern, (fullMatch, fromPart, toPart) => {
return fromPart + 'XXX' + toPart;
});
console.log(replaced);
要能够更改开始和 end 模式以匹配(也称为参数化),请使用函数中的参数构造RegExp
:>
const string = "This is my string that I need to replace a part FROM to a part TO.";
function parameterizedReplace(string, from, to, replacement) {
return string.replace(new RegExp('(' + from + ' ).*?( ' + to + ')'), '$1' + replacement + '$2');
}
const replaced = parameterizedReplace(string, 'FROM', 'TO', 'XXX');
console.log(replaced);
const string = 'This is my string that I need to replace a part FROM to a part TO.';
function parameterizedReplace(string, from, to, replacement) {
return string.replace(new RegExp(`(${from} ).*?( ${to})`), `\$1${replacement}\$2`);
}
const replaced = parameterizedReplace(string, 'FROM', 'TO', 'XXX');
console.log(replaced);
答案 3 :(得分:-1)
替换不是很简单吗?请注意,如果您正在搜索的字符串有多个实例,所有这些实例都将被替换。
var str = "This is my string that I need to replace a part FROM to a part TO.";
var res = str.replace("to a part", "XXX");