totalnoob
totalnoob

Reputation: 2741

dynamically add name attribute to tags within string - react / js

simplifying the existing post.

say I have a string

let someText = "<h1>test</h1><p>desc of test</p>"

I'd like to use React or javascript to change that to

someText = "<h1 id="test">test</h1><p>desc of test</p>"

for a table of contents type of functionality for any headers can be anchored from elsewhere on the page

I'm using react on the frontend and can also use jquery/jsdom on the backend with express

Upvotes: 0

Views: 620

Answers (2)

Chris
Chris

Reputation: 59491

Ok, here is my solution:

let str = `<h1>topic 1</h1>
<p>desc of topic 1</p>

<h1>topic 2</h1>
<p>desc of topic 2</p>`;

const innerHTMLarr = str.match(/<h1>.*(?=<\/h1>)/g).map(x => x.substring(4));

const result = str.replace(/<h1>/g, function() {
  return `<h1 id="${innerHTMLarr.shift()}">`;
});

console.log(result)

First I match every <h1> in a regex. I have added a look-ahead to match the closing </h1> but without actually including it in the result. The same cannot be done for the opening <h1> since JavaScript doesn't support look-behinds (as far as I know), so we have to remove it manually with substring().

Once we have the innerHTML for each <h1> tag, we can do a replace() on the whole string by finding with regex "<h1>" and replacing it with "<h1 id=[x]>", where x the first result of the array we populated above. We do shift() here to remove used values.

NOTE: The above will generate an invalid id attribute since you can't have spaces in the attribute value. You may want to expand my answer for your specific use-case.

Upvotes: 1

ninesalt
ninesalt

Reputation: 4354

I don't really understand what you're trying to do here, but based on your example, a simple replace should work fine.

let someText = "<h1>test</h1><p>desc of test</p>"
let idInfo = "id='test'"
let replaced = someText.replace("<h1>", `<h1 ${idInfo}>`)

console.log(replaced);

Upvotes: 0

Related Questions