Question

The rich text editor fields continually add extra zero width spaces to the text we enter into multiline fields. The content is then often messed up in display because of the characters.

I found this blog with some code to use jQuery and replace the characters. It doesn't tell how or when to implement the code. So I thought I would use the PreSaveAction on our edit form.

I added a script editor and the following code.

function PreSaveAction(){
  // remove all the zero width spaces ​ from the fields.
  $('.ms-rtestate-field').each(function(index,element)  {
       var exp = new RegExp(String.fromCharCode(8203),"g")
       var editor= $(element);
       var newText = editor.html().replace(exp,'');
       console.log("Old text: "+editor.html());
       editor.html(newText);
       console.log("New text: "+editor.html());
  });
  return true;
}

The code runs and removes the zw spaces, but any changes the user made are not saved. The console logs show the text and the second log shows that the new text was put back in, but when I come back into the edit for the text is like it was before. For example if we start with some text like this

So#&8203;me#&8203;#&8203; text

And then the user typed in some more, so it looked like this

So#&8203;me#&8203;#&8203; text. A new line goes here.

The PreSaveAction code would run and remove the extra spaces. But when I come back into the edit form I see

So#&8203;me#&8203;#&8203; text

Not sure what I need to do to remove these spaces, but I really need a solution. Anybody have any ideas? Thanks.

Was it helpful?

Solution

I think the problem was trying to access which element on the page would be updated during a save. I can't remember where I found it, but I need to use [contenteditable=true] as my selector. So this is the code I've been using for a bit.

function PreSaveAction(){
  // remove all the zero width spaces ​ from the fields.

  $('.ms-rtestate-field div[contenteditable=true]').each(function(index,element)  {
       var exp = new RegExp(String.fromCharCode(8203),"g");
       var editor= $(element);
       var txt = editor.html()
           txt = txt.replace(exp,'');
           txt = txt.replace(/ /g,' ')
           txt = txt.replace(/ {2,}/g,' ');
       editor.html(txt);
  });

  return true;
}

We also had a problem with lots of non-breaking spaces as well. So I remove those as well. I should probably update that to allow one...

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top