JavaScript .replace only replaces first Match

JavaScript .replace only replaces first Match

Asked on January 8, 2019 in Regex.
Add Comment


  • 3 Answer(s)

    Need  /g for this method,and try this code:

    var textTitle = "this is a test";
    var result = textTitle.replace(/ /g, '%20');
     
    console.log(result);
    

    The default .replace() is to replace only the first match, the  /g modifier is to replace all occurrences.To play use this link.

    Answered on January 8, 2019.
    Add Comment

    Use a regex inspite of a string for the first argument:

    "this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"
    
    
    Answered on January 8, 2019.
    Add Comment

    var new_string=old_string.replace( / (regex) /g, replacement_text);

    Answered on January 26, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.