-2

I'm on react and i'm working on a input that display Url path like wordpress page title, you put a title in the input and it display the path of the page onBlur...

I managed to do the whole thing but i still need a custom regex to display the Url for the value of the input:

using (.replace())

  • I need to trim the white space at the end and at the beginning
  • replace all the white space by ('-') but prevent from having 2 in a row
  • replace the specials characters by ('-')
  • replace letters like ç ñ ö é ì .etc by c n o e i

is there someone who can help me with that?

Aastone
  • 123
  • 2
  • 9

1 Answers1

0

Here's my take. You'll need to add some lines for additional diacritic characters (accented characters) that you want to replace. Here's a reference for someone else who did it.

Update: using .normalize instead of specifying each diacritic replacement

function clearResult(){
  document.getElementById('result').value = "";
}

function stripUrl(){

  var text = document.getElementById('input').value;

  var newText = text.trim()
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^\w/:.]/gi, '-') //clean up special characters
    .replace(/-{2,}/gi,'-'); //handle multiple dashes

  document.getElementById('result').value = newText;
}
<input id="input" type="text" value="https://google.com/)!(#$!*$ assfsd/       /mañana/aaa" style="width:500px;" onchange="clearResult()"/>
<button onclick="stripUrl()">StripUrl</button>
<br/>
<input type="text" id="result" style="width:500px;"/>
TabsNotSpaces
  • 1,224
  • 10
  • 22
  • I use this replacing all the .replace(...) by .normalize('NFKD') for the diacritics but i noticed that when i type ça va? it displays c-a-va while i need it to be ca-va same thing for mañana which displays man-ana how can i fix that? – Aastone Dec 04 '18 at 22:17
  • I added in the replacement for ñ above as an additional example. It returns "manana". If you add the same replace for your "c" diacritics, it will work as intended – TabsNotSpaces Dec 04 '18 at 22:26
  • doesn't work for me cause i edited the code like this https://codepen.io/Aastone/pen/gQJRWV – Aastone Dec 04 '18 at 22:41
  • @user3359675 ah, missed that you're using `.normalize`. This method ensures that the diacritics are unicode, then we can replace the unicode characters with their ascii counterparts (better explanation [here](https://stackoverflow.com/a/37511463/4705727)). Otherwise, answer has been updated – TabsNotSpaces Dec 04 '18 at 23:39
  • Thanks working good, if someone else is finding this and want to use it and using french language add this .replace(/[œ]/g,"oe") so you can get for example the word coeur when you writing cœur instead of c-ur – Aastone Dec 05 '18 at 00:12
  • @user3359675 glad to help. please mark this as the answer when you get the chance – TabsNotSpaces Dec 05 '18 at 15:31