Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript character replace all [duplicate]

Tags:

javascript

I am trying to find all the characters ('?') of a URL and replace it with &.

For instance, i have var test = "http://www.example.com/page1?hello?testing";

I first attempted:

document.write(test.replace("&","?"))

This resulted in that only the first ? would be replaced by & , then I found a question saying that I could add a g(for global)

document.write(test.replace("&"g,"?"))

Unfortunately, this did not have any effect either.

So how do I replace all characters of type &?

like image 487
Marc Rasmussen Avatar asked Dec 02 '13 12:12

Marc Rasmussen


People also ask

How do you replace every instance of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

How do you remove all occurrences of a character from a string in JS?

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.

How do you replace a character in a string in JavaScript?

Y ou can use the replace () method in JavaScript to replace the occurrence of a character in a string. However, the replace () method will only replace the first occurrence of the specified character. To replace all occurrences, you can use the global modifier (g).

What is replaceAll () in JavaScript?

String.prototype.replaceAll() - JavaScript | MDN The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. Skip to main content Skip to search Skip to select language

How to replace the occurrence of a character in a string?

Y ou can use the replace () method in JavaScript to replace the occurrence of a character in a string. However, the replace () method will only replace the first occurrence of the specified character.

What is the difference between pattern and replacement in JavaScript?

The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged. Can be a string or an object with a Symbol.replace method — the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.


1 Answers

You need to escape the ? character like so:

test.replace(/\?/g,"&")
like image 119
EasyPush Avatar answered Oct 02 '22 09:10

EasyPush