0

I have simple string

 const string = 'or id 671674205=##=2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 2146263624=##=2012-02-03 18:35:34 SampleClass1 [TRACE] verbose detail for id 619472373=##=2012-02-03 18:35:34 SampleClass5 [TRACE] verbose detail for id 1391429871=##=2012-02-03 18:35:34 SampleClass1 [DEBUG] detail for id 1522968690=##=2'

I want to replace =##= with <br/> and tried this

string.replace(/=##=/g, '<br/>')
console.log(string)

But didn't work... Please help to resolve this

Dark Knight
  • 995
  • 4
  • 22
  • 48

4 Answers4

2

Assign modified string to original string due to this you will have to change const to let or you can save in other variable.

let string = 'or id 671674205=##=2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 2146263624=##=2012-02-03 18:35:34 SampleClass1 [TRACE] verbose detail for id 619472373=##=2012-02-03 18:35:34 SampleClass5 [TRACE] verbose detail for id 1391429871=##=2012-02-03 18:35:34 SampleClass1 [DEBUG] detail for id 1522968690=##=2';

string = string.replace(/=##=/g, 'aaa')
console.log(string)
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
1

From MDN docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

The replace() method returns a new string with some or 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.

let string = 'or id 671674205=##=2012-02-03 18:35:34 SampleClass3 [DEBUG] detail for id 2146263624=##=2012-02-03 18:35:34 SampleClass1 [TRACE] verbose detail for id 619472373=##=2012-02-03 18:35:34 SampleClass5 [TRACE] verbose detail for id 1391429871=##=2012-02-03 18:35:34 SampleClass1 [DEBUG] detail for id 1522968690=##=2';
console.log("original string");
console.log(string)

string = string.replace(/=##=/g, 'aaa')
console.log("Updated string");
console.log(string)
Hiteshdua1
  • 2,126
  • 18
  • 29
1

JavaScript String are immutable. You cannot alter a string. String operations trim slice replace return a new string. You can do this

const myString = string.replace(/=##=/g, '<br/>');
console.log(myString);
Sakhi Mansoor
  • 7,832
  • 5
  • 22
  • 37
1

The replace() method returns the replaced string that matches the given regex. In your code you are missing to overwrite the value of string variable with the replaced one as you are expecting the replaced value to be in stringvariable. Thus you need to do

//assign replaced value to `string` and overwrite the old value
string = string.replace(/=##=/g, '<br/>');
console.log(string)
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62