1

I have a string like this

"#G=0&path=folder1"

I want to find a part after "path=" which is folder1 in this case, and replace it with something else, so the string will look like this:

"#G=0&path=file2"

How can I do this using Javascript regular expressions?

1
  • Are you using a document fragment as a query-string? Parsing query strings correctly is a bit more work than one simple regex. Commented Jan 18, 2013 at 19:50

2 Answers 2

1

One possible regex solution:

"#G=0&path=folder1".replace(/(&?path=).*$/, "$1" + "file2");

Or you can do it without regex:

str.substring(0, str.lastIndexOf("=") + 1) + "file2";
Sign up to request clarification or add additional context in comments.

Comments

0

See, for example, Regular-Expressions.info, MDN replace and here, and educate yourself about regular expressions, they are very useful.

var str = '#G=0&path=folder1';
var file = 'file2';

str = str.replace( /^(#G=0&path=).+$/, '$1' + file );

console.log( str );    // #G=0&path=file2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.