How can I perform a str_replace in JavaScript, replacing text in JavaScript?

后端 未结 22 1797
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 00:29

I want to use str_replace or its similar alternative to replace some text in JavaScript.

var text = \"this is some sample text that i want to re         


        
相关标签:
22条回答
  • 2020-12-01 01:10
    function str_replace($old, $new, $text)
    {
       return ($text+"").split($old).join($new); 
    }
    

    You do not need additional libraries.

    0 讨论(0)
  • 2020-12-01 01:14

    All these methods don't modify original value, returns new strings.

    var city_name = 'Some text with spaces';
    

    Replaces 1st space with _

    city_name.replace(' ', '_'); // Returns: Some_text with spaces
    

    Replaces all spaces with _ using regex. If you need to use regex, then i recommend testing it with https://regex101.com/

    city_name.replace(/ /gi,'_');  // Returns: Some_text_with_spaces 
    

    Replaces all spaces with _ without regex. Functional way.

    city_name.split(' ').join('_');  // Returns: Some_text_with_spaces
    
    0 讨论(0)
  • 2020-12-01 01:15

    that function replaces only one occurrence.. if you need to replace multiple occurrences you should try this function: http://phpjs.org/functions/str_replace:527

    Not necessarily. see the Hans Kesting answer:

    city_name = city_name.replace(/ /gi,'_');
    
    0 讨论(0)
  • 2020-12-01 01:17

    If you don't want to use regex then you can use this function which will replace all in a string

    Source Code:

    function ReplaceAll(mystring, search_word, replace_with) 
    {
        while (mystring.includes(search_word))
        {
            mystring = mystring.replace(search_word, replace_with);
        }
    
        return mystring;  
    }
    

    How to use:

    var mystring = ReplaceAll("Test Test", "Test", "Hello"); 
    
    0 讨论(0)
提交回复
热议问题