Javascript获取具有多个相同字符的子字符串

时间:2017-11-29 18:39:39

标签: javascript

假设我有字符串:

var post = "[PostContent(postId=123e4567-e89b-12d3-a456-426655440000, postName=My New House, picture=house.jpg, location=San Francisco)]"

我试图破解的是postId中的UUID,因此新生成的字符串只有值:

123e4567-e89b-12d3-a456-426655440000

感谢您的帮助!

更新

对于我已经尝试过的不完整的问题感到抱歉:

var firstvariable = "postId=";
var secondvariable = ", postName=";
string.match(new RegExp(firstvariable + "(.*)" + secondvariable));

string.substring(string.lastIndexOf("postId=")+1,string.lastIndexOf(", postName"));

var regex = /(.*postId=\s+)(.*)(\s+, postName.*)/;
var newtext = string.replace(regex, "$2");

1 个答案:

答案 0 :(得分:4)

您可以使用String#match方法。

var post = "[PostContent(postId=123e4567-e89b-12d3-a456-426655440000, postName=My New House, picture=house.jpg, location=San Francisco)]";

console.log(
  post.match(/postId=([\w-]+)/)[1]
)

Regex explanation here