I have a texteditor (div) and there's a function to format the (selected)text inside it. When I mark a part of the text and chose to make it look like this
(code snippet) I have to use
to avoid some bugs and make it user-friendly. However this data is being sent to the server (nodeJS) and it causes a bug where the content splits up into an object and to avoid this issue, I wanted to replace
with a space before sending it to the server.
What I did was the following
// replace by " "
let content = $('.editor').html().replace(/( )/gi, " ");
// replace editor html
$('.editor').html(content);
// print results
console.log("html: ",$('.editor').html());
in console it displays what is expected (text : as <code>dasdasd</code>
):
html: as<span> </span><code>dasdasd</code><span> </span>
however on the serverside i got the following error:
TypeError: Cannot convert object to primitive value
then i decided to print the variable which contains the content from editor (which seems fine?):
{ posterContent: 'as<span> </span><code>dasdasd</code><span> </span>' }
Question: how can I replace
with a space without having to convert html to (string) in order to avoid this error?
I know you solved the problem, but you might be interested in reading this, because your problem arised from a misunderstood basic concept of web dev which is data encoding.
As far as I understand, you can't pass the string
to your back-end because it's parsed as an object, so I assume you either used GET or POST's application/x-www-form-urlencoded
encoding to send request. In simpler terms:
// this object
{
a: 10,
b: 20
}
// get passed to the server as this string
a=10&b=20
Which is fine. That's one way to do. But you have to deal with proper encoding for sending special characters, example:
// you have this object:
{
a: 10,
b: 'hello&world'
}
// you encode it naively to this
a=10&b=hello world
// the server understands this
{
a: 10,
b: 'hello',
nbsp: ';world'
}
The &
creates the bug, because it's a special character and won't be treater as part of a string. Even if you find a trick to not use  
, or to replace it by a space, you'll think you have solved the problem, but... almost all unicode characters are special characters and need to be encoded so as to not create bugs .
Encode your strings using encodeURIComponent
, or POST your data with a different encoding (for example, JSON). I'd personally use a function like fetch
which does all the job for you and spare you with all the encoding-related issues:
let data = { userId: 1, id: 1 } fetch('https://jsonplaceholder.typicode.com/posts',{ method: 'POST', data: JSON.stringify(data) }) .then(resp => resp.json()) .then(json => console.log(json));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.