Home > Net >  JavaScript Regex - add ~ symbol between lettes except letter after space
JavaScript Regex - add ~ symbol between lettes except letter after space

Time:10-12

how can I put ~ symbol between letters except the first letter after space? Here is what I got from this site by trying here and there.

txt = text.split(/  ?/g).join(" ");
txt.replace(/(.)(?=.)/g, "$1~")

this regex output as

input = "hello friend"
output = "h~e~l~l~o~ ~f~r~i~e~n~d"

How to output "h~e~l~l~o~ f~r~i~e~n~d"?

CodePudding user response:

Use \S instead of . when matching the character you want to insert a ~ next to - \S matches any non-space character, whereas . matches any non-newline character.

const text = 'hello friend';
const singleSpaced = text.split(/  /g).join(" ");
const output = singleSpaced.replace(/(\S)(?=.)/g, "$1~");
console.log(output);

or

const text = 'hello friend';
const output = text
  .replace(/  /g, ' ')
  .replace(/(\S)(?=.)/g, "$1~");
console.log(output);

CodePudding user response:

You can do this in one operation with a replace using this regex:

(?<=\S)(?!$)

It matches the position after a non-whitespace character (?<=\S) except for the position at end of string (?!$). You can then insert a ~ at those positions:

text = "hello friend"
txt = text.replace(/(?<=\S)(?!$)/g, '~') 

console.log(txt)

CodePudding user response:

You could match a single non whitespace char, and assert that to the right is not optional whitespace chars followed by the end of the string.

In the replacement use the full match followed by a tilde $&~

\S(?!\s*$)

See a regex demo.

input = "hello friend"
output = input.replace(/\S(?!\s*$)/g, '$&~') 

console.log(output)

  • Related