Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-7
rated 0 times [  0] [ 7]  / answers: 1 / hits: 96305  / 12 Years ago, fri, december 28, 2012, 12:00:00

I'm trying to do replace in JavaScript using:



r = Inamnhere;
s = r.replace(n, );


But instead of giving me




I am here




as the value of s,
It returns the same.



Where's the problem??


More From » replace

 Answers
9

As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.


var r = "Inamnhere";
var s = r.replace(/n/g,' ');

I would like to point out the difference from what was going on from the start.
you were using the following statements


var r = "Inamnhere";
var s = r.replace("n"," ");

The statements are indeed correct and will replace one instance of the character n. It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.


For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with n or r where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.


var r = "Iramnhere";
var s = r.replace(/[nr]/g,' ');

[#81183] Thursday, December 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;