1

I am developing a javascript tool that will extract the string, obtain relevant strings and create html tags.

const string = "Create heading 1 that will have class abc and id xyz";

const elementList = [
{name: 'heading 1', tag: 'h1'},
{name: 'heading 2', tag: 'h2'}
{name: 'paragraph', tag: 'p'},
];

function convertTag(input) {
  return elementList.reduce((acc, a) => {
  const re = new RegExp(a.name,"g");
  return acc.replace(re, a.tag);
  }, input);
}

let initialString = convertTag(string)
//returns create h1 that will have class abc and id xyz
let htmlElement = initialString. split (" ")[1];  // will return h1
let code = `<${htmlElement}> </${htmlElement}>`;

How do I include class and Id? There might be other attributes like alt, src etc. Is there any library to grab the HTML attributes?

Thank you

4
  • initialString. split (" ")[6]; and initialString. split (" ")[9];? And then add those to let code...? Commented Jun 5, 2020 at 9:49
  • @TorbjörnStabo, the problem is the string might consist "Embed an image with source test.c and alt test and class responsive" Commented Jun 5, 2020 at 9:54
  • Can you not list all the attributes and map the string and then take the next word of the attributes? Commented Jun 5, 2020 at 9:57
  • @BinitaGyawali Sure. Have an array with the attributes you'd like to allow, class, id, alt, src, etc. Then extract each using something like string.split(" ")[string.split(" ").indexOf("class")+1]. Commented Jun 5, 2020 at 10:30

1 Answer 1

1

The result of running the following code is abc xy being printed in the console. The idea is to search for the prefix "class " and "id " then grab 1 or more alphanumeric characters, bunch em together and return them. The match function returns a bunch of things, including the position within the string. Since we're just interested in the 1st (only!) result, we can grab element 0 from the result, treating it like a simple array.

The half-awake will note that these simple regexes would allow number to start the following group. Rather than grabbing 1 or more alphanumerics, I suppose a more robust solution would be to grab 1 alpha AND 0 or more alphanumerics.

Someone put me onto Expresso as a useful (free) tool to play around with regexes on the desktop.

function test1()
{
    const s = 'Create heading 1 that will have class abc and id xy';
    let cl = s.match(/(?<=class )\w+/)[0];
    let id = s.match(/(?<=id )\w+/)[0];
    console.log(cl,id);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.