Anirudh Anirudh - 2 months ago 5
C# Question

Find and replace content within string (C#)

The below string is coming from a DIV tag. So I have enclosed the value below.

String cLocation = "'target="_blank'></a><img alt='testimage.jpg' src='/SPECIMAGE/testimage.jpg'"


I would like to replace in the above string by changing
"src="/"
with
"src='xyz/files'"
.

I have tried the typical
string.Replace("old","new")
but it didn't work.

I tried the below,

cNewLocation ="xyz/files";
cNewString = cLocation.Replce("src='/'", "src='" + cNewLocation + "'/")


It didn't work.

Please suggest.

Answer

If I'm understanding what you're asking, you could use Regex to replace the string like so:

var cNewString = Regex.Replace(cLocation, @"src='/.*/", "src='" + newLocation + "/");

EDIT : I modified the regular expression to replace src='/.../ with src='{newLocation}/

Comments