Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would use the replace method:

text = text.replace('old', 'new');

The first argument is what you're looking for, obviously. It can also accept regular expressions.

Just remember that it does not change the original string. It only returns the new value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...