replace space with dash JavaScript

后端 未结 5 638
予麋鹿
予麋鹿 2020-12-17 23:29
var html = \"
\"+title+\"
\"; document.write(title.replace(/ /g,\"-\")); html+= \'

Detail

相关标签:
5条回答
  • 2020-12-18 00:14

    Calling title.replace will not change title, but return a string where the values have been replaced. You need to use the returned value:

    var html = "<div>"+title+"<br/>";
    var newTitle = document.write(title.replace(/ /g,"-"));
    html+= '<p><a href="go.aspx?title=' + newTitle + '">Details<\/a></p></div>';
    

    The regular expression is fine, but will only replace spaces and not all whitespace.

    0 讨论(0)
  • 2020-12-18 00:15

    ehdv's answer gets you 90% of the way there. I just wanted to clarify where the code he suggested would go within your code, and it wouldn't look right in a comment.

    var html = "<div>" + title + "<br/>";
    title = title.replace(/\s/g , "-");
    html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p></div>';
    

    This assumes that you DON'T want dashes in the div, but you DO in the URL.

    And if you also want to replace multiple spaces that come immediately one after another with a SINGLE dash instead of ending up with double dashes in your title, use this instead:

    var html = "<div>" + title + "<br/>";
    title = title.replace(/\s+/g , "-");
    html+= '<p><a href="go.aspx?title=' + title + '">Details<\/a></p>
    

    I'd also like to mention that you're not closing your div. Maybe you just didn't include that part of your code but it's worth mentioning. There's also an unnecessary \ in your string. It's not hurting anything, but it's not needed. Maybe your code is meant to look like this:

    var html = "<div>" + title + "</div>";
    title = title.replace(/\s/g , "-");
    html+= '<p><a href="go.aspx?title=' + title + '">Details</a></p>
    
    0 讨论(0)
  • 2020-12-18 00:22

    var str = "Tatwerat Development Team";
    str = str.replace(/\s+/g, '-');
    document.write(str)

    0 讨论(0)
  • 2020-12-18 00:25

    Try title.replace(/\s/g , "-") instead. (/\s/ is the regex escape for whitespace).

    Also, do:

    title = title.replace(/\s/g , "-");
    var html = "<div>" + title + "</div>";
    // ...
    
    0 讨论(0)
  • 2020-12-18 00:27

    I find regex expressions commonly used in the replace function very hard to read - plus it's easy to forget to not quote the string you are searching for or to omit the /g to indicate a global replace. For doing something simple like replacing a space with a dash, using an easier to understand "split" followed by a "join" is just as fast.

    alert("this is a test".split(" ").join("-"));
    

    https://jsfiddle.net/n0u3aw5c/

    0 讨论(0)
提交回复
热议问题