ChatGPT解决这个技术问题 Extra ChatGPT

JavaScript .replace only replaces first Match [duplicate]

This question already has answers here: How to replace all occurrences of a string in JavaScript (79 answers) Closed 2 years ago.

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

But the replace functions stops at the first instance of the " " and I get the

Result : "this%20is a test"

Any ideas on where Im going wrong im sure its a simple fix.

In this case, replace( ) is a JavaScript String method. No jQuery involved.
+1 for not using jQuery

J
Jonathan

You need a /g on there, like this:

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

You can play with it here, the default .replace() behavior is to replace only the first match, the /g modifier (global) tells it to replace all occurrences.


Did exactly what was needed. Thank you.
For replacing a pipe, see this.
N
Nikita Rybak
textTitle.replace(/ /g, '%20');

J
Jhonny D. Cano -Leftware-

From w3schools

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Would be better to use a regex here then:

textTitle.replace(/ /g, '%20');

thanks for the reference, it's not an easy example to follow with the blank space being the replace value (e.g. / /g).
J
J. Holmes

Try using a regex instead of a string for the first argument.

"this is a test".replace(/ /g,'%20') // #=> "this%20is%20a%20test"


N
Nigrimmist

The same, if you need "generic" regex from string :

const textTitle = "this is a test"; const regEx = new RegExp(' ', "g"); const result = textTitle.replace(regEx , '%20'); console.log(result); // "this%20is%20a%20test" will be a result


S
Subham Debnath

For that you neet to use the g flag of regex.... Like this :

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

That sh


a
amfeng

Try using replaceWith() or replaceAll()

http://api.jquery.com/replaceAll/


Didn't he ask for a JQuery version? I don't see a .replace() in the JQuery API - that's vanilla Javascript.
@Nick Are you jealous or what? :)
@Nikita - No...this isn't at all relevant to the question. the OP is mistaken including jQuery in there at all, this is vanilla JavaScript, having nothing to do with jQuery or it's replace methods...
@Nick: Fair enough I guess; I'm just trying to give him what he asked for.
@afeng - I understand that, try and read the entire question though, not the title only...the question is about the .replace() string operator, no jQuery involved, it's a common mix-up, unfortunately.