I have a pretty long string. Before I databind the string, I want to be able to modify the string by inserting some more text. For example, I have a string <a href="/a/info/a.html"><img src="/userimage/imgs.jpg"/></a> I need to insert http://m.mydom.com right before the /a and right before /userimage. Note, this will always be the same so it is safe to say that the string I want to add to will be consistent. I would like to do this either with lamda or just c#. Thanks for any help.
-
So is the user not currently on m.mydom.com?scottheckel– scottheckel2012-05-30 02:37:43 +00:00Commented May 30, 2012 at 2:37
3 Answers
If you need to do this for all relative paths on your page, using C# to accomplish this is actually not the best tool for this.
HTML comes with an element called base (see spec information) that is used to specify a document's base URI explicitly. If you changed your HTML to something like the following:
<head>
<base href="http://m.mydom.com">
</head>
<body>
<a href="/a/info/a.html"><img src="/userimage/imgs.jpg"/></a>
</body>
Both the image and the anchor will point to the correct base. Don't believe me? Check out this jsFiddle demonstating the amazingness of base.
Comments
Cant you just use String.Replace?
var s = "<a href=\"/a/info/a.html\"><img src=\"/userimage/imgs.jpg\"/></a>";
s.Replace("\"/a","\"http://m.mydom.com/a").Replace("\"/userimage", "\"http://m.mydom.com/userimage");
Not the nicest method, you could always use a RegEx.
Comments
You can use a simple regular expression:
var regex = new Regex("(?<=(src|href)=\")([^\"]*)");
var s = "<a href=\"/a/info/a.html\"><img src=\"/userimage/imgs.jpg\"/></a>";
Console.WriteLine(regex.Replace(s, "http://m.mydom.com$0"));
(?<=...) is a lookbehind; $0 is the content of the capturing group 0, which is the content of the link before the replacement.