locked
Regex to replace spaces with underscores RRS feed

  • Question

  • User359558855 posted

    The intention:

    Dynamically generate collapsible content from a directory with subdirectories containing images.

    The problem:

    The generated href from the directory names occasionally contain spaces. The same directory name var is used to generate IDs for the matching <div>. the ID name cannot contain spaces. I would like to replace the spaces with a usable character to create a valid ID name.

    The question:

    Where and how would I code to replace the spaces with underscores in @dir.Name, without renaming the original directory? I believe the answer lies in the use of @Regex.Replace but do not know the how/where part.

    Can anyone assist me or point me to a good reference for this situation? I'm fairly new to programming.

    Thank you.

    The code:

    @{

        var photofolderpath = Server.MapPath("~/Photos");
        var directoryInfo = new DirectoryInfo(photofolderpath);
        var photodirectories = directoryInfo.GetDirectories("*.", SearchOption.AllDirectories);

    }

    <div class="accordion" id="gallery" data-toggle="modal-gallery" data-target="#modal-gallery">
        @foreach(var dir in photodirectories){
            <div class="accordion-group">
                <div class="accordion-heading">
                    <a class="accordion-toggle" data-toggle="collapse" data-parent="#gallery" href="#@dir.Name">
                        <h4><i class="icon-plus-sign"></i> @dir.Name</h4>
                    </a>
                </div>
                <div id="@dir.Name" class="accordion-body collapse">
                    <div class="accordion-inner">
                        <ul style="list-style-type: none;">
                            @foreach(var file in dir.GetFiles()){
                                <li>
                                    <a href="~/Photos/@dir.Name/@file.Name" title="@file.Name" class="polaroid" alt="@file.Name" data-gallery="gallery">@file.Name</a>
                                </li>
                                }
                        </ul>
                    </div>
                </div>
                </div>
            }
    </div>

    Friday, May 17, 2013 6:08 PM

Answers

  • User-183374066 posted

    You can use simple replace .. No need of Regex

    @dir.Name.Replace(" ","_")

    Regards.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 17, 2013 6:37 PM

All replies

  • User-183374066 posted

    You can use simple replace .. No need of Regex

    @dir.Name.Replace(" ","_")

    Regards.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 17, 2013 6:37 PM
  • User359558855 posted

    The reply:

    Incredibly elegant solution. Thank you very much.

    Friday, May 17, 2013 6:51 PM