How can I perform a str_replace in JavaScript, rep

2020-01-29 04:05发布

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 replace";
var new_text = replace_in_javascript("want", "dont want", text);
document.write("new_text");

should give

this is some sample text that i dont want to replace

If you are going to regex, what are the performance implications in comparison to the built in replacement methods.

21条回答
▲ chillily
2楼-- · 2020-01-29 04:11

hm.. Did you check replace() ?

Your code will look like this

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);
查看更多
走好不送
3楼-- · 2020-01-29 04: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
查看更多
疯言疯语
4楼-- · 2020-01-29 04:14

You have the following options:

  1. Replace the first occurrence

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace('want', 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well"
console.log(new_text)

  1. Replace all occurrences - case sensitive

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/g, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i WANT to replace as well
console.log(new_text)

  1. Replace all occurrences - case insensitive

var text = "this is some sample text that i want to replace and this i WANT to replace as well.";
var new_text = text.replace(/want/gi, 'dont want');
// new_text is "this is some sample text that i dont want to replace and this i dont want to replace as well
console.log(new_text)

More info -> here

查看更多
一纸荒年 Trace。
5楼-- · 2020-01-29 04:16

There are already multiple answers using str.replace() (which is fair enough for this question) and regex but you can use combination of str.split() and join() together which is faster than str.replace() and regex.

Below is working example:

var text = "this is some sample text that i want to replace";

console.log(text.split("want").join("dont want"));

查看更多
女痞
6楼-- · 2020-01-29 04:16

In Javascript, replace function available to replace sub-string from given string with new one. Use:

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
console.log(new_text);

You can even use regular expression with this function. For example, if want to replace all occurrences of , with ..

var text = "123,123,123";
var new_text = text.replace(/,/g, ".");
console.log(new_text);

Here g modifier used to match globally all available matches.

查看更多
你好瞎i
7楼-- · 2020-01-29 04:19

If you really want a equivalent to PHP's str_replace you can use Locutus. PHP's version of str_replace support more option then what the JavaScript String.prototype.replace supports. For example tags:

//PHP
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
//JS with Locutus
var $bodytag = str_replace(['{body}', 'black', '<body text='{body}'>')  

or array's

//PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
//JS with Locutus
var $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
var $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

Also this doesn't use regex instead it uses for loops. If you not want to use regex but want simple string replace you can use something like this ( based on Locutus )

function str_replace (search, replace, subject) {

  var i = 0
  var j = 0
  var temp = ''
  var repl = ''
  var sl = 0
  var fl = 0
  var f = [].concat(search)
  var r = [].concat(replace)
  var s = subject
  s = [].concat(s)

  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + ''
      repl = r[0]
      s[i] = (temp).split(f[j]).join(repl)
      if (typeof countObj !== 'undefined') {
        countObj.value += ((temp.split(f[j])).length - 1)
      }
    }
  }
  return s[0]
}
var text = "this is some sample text that i want to replace";

var new_text = str_replace ("want", "dont want", text)
document.write(new_text)

for more info see the source code https://github.com/kvz/locutus/blob/master/src/php/strings/str_replace.js

查看更多
登录 后发表回答