This question already has an answer here:
这个问题在这里已有答案:
- How do you use a variable in a regular expression? 17 answers
- 如何在正则表达式中使用变量? 17个答案
Given :
鉴于:
-
A string e.g.
字符串,例如
Username="don" Password="somethingcalledpassword" Url="someurl"
-
Prefix of the search-string Password="
搜索字符串的前缀Password =“
- Suffix of the search-String suffix="
- search-String suffix =“的后缀
Aim: Search and replace all the substrings of the main string that start with the prefix and end with the suffix (first occurrence).
目标:搜索并替换以前缀开头并以后缀(第一次出现)结束的主字符串的所有子字符串。
E.g.
例如。
var str = "Username=\"don\" Password=\"somethingcalledpassword\"
Url=\"someurl\"";
//replace somethingcalledpassword with new password.
2 个解决方案
#1
0
You can replace the text that matches the following regular expression:
您可以替换与以下正则表达式匹配的文本:
/Password="[^"]*"/
So the complete code is:
所以完整的代码是:
var str = "Username=\"don\" Password=\"somethingcalledpassword\" Url=\"someurl\"";
var newpassword = "anewpassword";
var st2 = str.replace(/Password="[^"]*"/, "Password=\""+newpassword+"\"");
#2
1
As per my understanding you want to replace just a string.
根据我的理解,你想要只替换一个字符串。
var replaceBetween = function(str, start, end, what) {
return str.substring(0, start) + what + str.substring(end);
};
var str = "Password=\"somethingcalledpassword\"";
alert(str);
var start = str.indexOf("\"") + 1;
var end = str.lastIndexOf("\"");
var str = replaceBetween(str, start, end, "newPassword");
alert(str);
Here is fiddle http://jsfiddle.net/murli2308/ao28y8x2/
这里是小提琴http://jsfiddle.net/murli2308/ao28y8x2/
#1
0
You can replace the text that matches the following regular expression:
您可以替换与以下正则表达式匹配的文本:
/Password="[^"]*"/
So the complete code is:
所以完整的代码是:
var str = "Username=\"don\" Password=\"somethingcalledpassword\" Url=\"someurl\"";
var newpassword = "anewpassword";
var st2 = str.replace(/Password="[^"]*"/, "Password=\""+newpassword+"\"");
#2
1
As per my understanding you want to replace just a string.
根据我的理解,你想要只替换一个字符串。
var replaceBetween = function(str, start, end, what) {
return str.substring(0, start) + what + str.substring(end);
};
var str = "Password=\"somethingcalledpassword\"";
alert(str);
var start = str.indexOf("\"") + 1;
var end = str.lastIndexOf("\"");
var str = replaceBetween(str, start, end, "newPassword");
alert(str);
Here is fiddle http://jsfiddle.net/murli2308/ao28y8x2/
这里是小提琴http://jsfiddle.net/murli2308/ao28y8x2/