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

后端 未结 22 1892
没有蜡笔的小新
没有蜡笔的小新 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: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
    

提交回复
热议问题