2

I am trying to replace all occurrences of line breaks to html line breaks in my string, but it is only converting the first one found

var output= "";
string x = "Hi\nMy name is x\nAnd age is 10\n";
output = x
output = output.replace("\\n", "<br>")

Output =

Hi
My name is x\nAnd age is 10\n
tester123
  • 399
  • 1
  • 3
  • 10
  • Output doesn't contains `
    `...
    – Jarod42 Feb 17 '21 at 14:47
  • @MarekR This is qml – tester123 Feb 17 '21 at 14:49
  • @Jarod42 Output first line break was replaced correctly. Obviously I mean output to screen not the output string itself – tester123 Feb 17 '21 at 14:50
  • `string::replace` != `QString::replace`. – Jarod42 Feb 17 '21 at 14:51
  • @Jarod42 I am actually using the [text](https://doc.qt.io/qt-5/qml-qtquick-text.html#text-prop), so it is a string – tester123 Feb 17 '21 at 14:55
  • 1
    [Doc says](https://doc.qt.io/qt-5/qml-string.html): `QML extends the JavaScript String type with a arg() function to support value substitution.`, So [read this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). – Marek R Feb 17 '21 at 15:00
  • @tester123 Duplicate of https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript, use `output = output.replace(new RegExp("\\n", 'g'), "
    ")`
    – eyllanesc Oct 31 '21 at 10:15
  • @eyllanesc: If you make this an answer, I can award my bounty to it. Otherwise it will just expire. Also, is QML strictly equivalent to ECMA script? Otherwise I would not consider this to be a duplicate. – mschilli Oct 31 '21 at 14:32
  • Yes, see https://doc.qt.io/qt-5/qtqml-javascript-hostenvironment.html: *Like a browser or server-side JavaScript environment, the QML runtime implements the ECMAScript Language Specification standard. This provides access to all of the built-in types and functions defined by the standard, such as Object, Array, and Math. The QML runtime implements the 7th edition of the standard.* – eyllanesc Oct 31 '21 at 16:21

1 Answers1

1

QML is just a very feeble front end to JavaScript. You need to use the JavaScript global option.

str.replace(/blue/g, "red");

In your case that would be:

output = output.replace("\\n/g", "<br>")
user3450148
  • 851
  • 5
  • 13