JavaScript .replace only replaces first Match

JavascriptRegexReplace

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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');

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

Try using replaceWith() or replaceAll()

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYardstermisterView Question on Stackoverflow
Solution 1 - JavascriptNick CraverView Answer on Stackoverflow
Solution 2 - JavascriptNikita RybakView Answer on Stackoverflow
Solution 3 - JavascriptJ. HolmesView Answer on Stackoverflow
Solution 4 - JavascriptJhonny D. Cano -Leftware-View Answer on Stackoverflow
Solution 5 - JavascriptSubham DebnathView Answer on Stackoverflow
Solution 6 - JavascriptNigrimmistView Answer on Stackoverflow
Solution 7 - JavascriptamfengView Answer on Stackoverflow