SolidSnake4444
SolidSnake4444

Reputation: 3587

How can I replace a string that is attached to another string?

I have a long description coming from a data source. The data can be 5,000 characters plus. We have a short one line description field that is not required. When it is not filled in, we use the first 128 characters from the description and append "..." to the final three. So 125 are the description and the last three are the "...".

We are running into issues with text to speech where the "..." attached to works come out said wrong. For example by a phrase can look like "beautiful home loca...".

I would like to find the "..." and then the word that is "attached" to it (by touching the word as in no spaces) and replace it with text along the lines of "truncated" or "view full description".

I'm aware of replace but that only takes in a hard string so I'm just replacing the "..." instead of that AND the word it is attached to.

Some examples of expected results:

welcome to this beautiful home -> welcome to this beautiful home
welcome to this beautiful h... -> welcome to this beautiful truncated
welcome to this beautiful ... -> welcome to this beautiful truncated

How can I accomplish this in JavaScript?

Upvotes: 0

Views: 126

Answers (3)

slider
slider

Reputation: 12990

String replace does consider regular expressions. So you can do something like this:

let strs = [
  'welcome to this beautiful home',
  'welcome to this beautiful h...',
  'welcome to this beautiful ...'
];

strs.forEach(s => console.log(s.replace(/\w*\.{3}/g, 'truncated')));

Upvotes: 5

ssc-hrep3
ssc-hrep3

Reputation: 16089

You could use a regex like this:

([^\s]*\.\.\.)$

and replace it with an empty string

Here is an example: https://regex101.com/r/QfnfVn/2


This regex selects any non white-space character, which is immediately followed by three dots at the end of the string as well as 3 dots at the end of the string without any non white-space character in front of it.

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 192857

You can use a regular expression (regex101):

const replaceEllipsis = (str) => str.replace(/\S*\.{3}$/, 'truncated');

console.log(replaceEllipsis('welcome to this beautiful home'));  //-> welcome to this beautiful home
console.log(replaceEllipsis('welcome to this beautiful h...'));  //-> welcome to this beautiful truncated
console.log(replaceEllipsis('welcome to this beautiful ...'));  //->  welcome to this beautiful truncated

Upvotes: 2

Related Questions