如何在Javascript中找到并替换给定前缀和字符串后缀的字符串? [重复]

时间:2022-09-13 12:20:18

This question already has an answer here:

这个问题在这里已有答案:

Given :

鉴于:

  1. A string e.g.

    字符串,例如

    Username="don" Password="somethingcalledpassword" Url="someurl"
    
  2. Prefix of the search-string Password="

    搜索字符串的前缀Password =“

  3. Suffix of the search-String suffix="
  4. 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/