PROBLEM
I have a string (in JavaScript) which may or may not contain one or more GUIDs at various places. These GUIDs are surrounded by single quotes. I need to remove the quotes.
WHAT I HAVE SO FAR
Regex to match GUIDs with single quotes:
var guid = /('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}')/ig;
a way to replace all single and double quotes:
myString = myString.replace(/["']/g, ""); // I actually don't need the double quote here...
But I am not sure how to replace each instance of a matched GUID with single quotes with the same GUID without the quotes... while still keeping any other single quotes in the string.
I am guessing I probably need to get all matches, loop through each of them and do a replacement.. in pseudo code:
var matches = myString.matches(guid);
foreach (var match in matches)
{
myString = myString.replace(match.value, match.value.replace("'", ""));
}
Can someone give me the above in jQuery or plain JS? Also, if there's a much simpler way to do it, that would be even better.
You're very close. Change that regex to include a capture group without the '
in it:
var guid = /'([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'/ig;
// Change ^^------------------------------------------------------------^^
then:
str = str.replace(guid, "$1");
$1
= the first capture group. Because of the g
on your regex, that will replace all occurrences in the string.
Live example:
var guid = /'([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})'/ig;
var str = "Testing '00b3dada-88d7-482a-b082-039cc7153023' and '30378f4e-889c-4a9a-854c-daa304969246' and '413db223-7c02-4f95-a994-8aaaad48a245'";
snippet.log("Before: " + str);
str = str.replace(guid, "$1");
snippet.log("After: " + str);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With