0

I have a api response that is a combination of plain text and image tag. What is the best way to separate plain text from the response? I need to separate plain text so I can style it separately.

This is the example of a response:

This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />
Andreas
  • 21,535
  • 7
  • 47
  • 56
user11399165
  • 101
  • 1
  • 10

5 Answers5

3

You can use regex to remove html tag like this

str = str.replace(/<(?:.|\n)*?>/gm, '');

or you this if only remove image tag str = str.replace(/<img .*?>/g, '');

var str = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
//str = str.replace(/<(?:.|\n)*?>/gm, '');
str = str.replace(/<img .*?>/g, '');
console.log(str);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
0

One approach might be to use the following regular expression /<img[\s\w=\":/.-]+>/gmi to match and replace the <img /> tag in your response string:

const responseText = `This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />`

const responseWithoutImageTag = responseText.replace(/<img[\s\w=\":/.-]+>/gmi, '')

console.log(responseWithoutImageTag)
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
0

A safer way than regular expressions is to parse the HTML and extract the text content:

var template = document.createElement('template');
template.innerHTML = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />';

template.content.textContent returns 'This is the cap you unscrew to open when you refuel your car '

Eric Eskildsen
  • 4,269
  • 2
  • 38
  • 55
  • Yes, that would be the way to go, but `.textContent` doesn't help with this part of the requirement: _"I need to separate plain text **so I can style it separately**"_ – Andreas Apr 23 '19 at 10:48
  • @Andreas True, but the gist of the question is how to separate them since how the style is applied depends on the method of rendering. – Eric Eskildsen Apr 23 '19 at 10:50
0

You can use substring from o to index of image tag

    var str = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'

var newStr = str.substring(0, str.indexOf('<img'));
console.log(newStr)
Syed Mehtab Hassan
  • 1,297
  • 1
  • 9
  • 23
0

Simply put, you could do this:

const textOnly = str.slice(0, str.indexOf('<img'));

If you want the image tag only:

const imageTag = str.slice(str.indexOf('<img'), str.length);

(substring works too, like in the answer by Syed)

Musonant
  • 81
  • 5