0

I have a large string with HTML tags which is store in mongodb. Now I only want replace the maxlength value. Using Jquery It's easy way to do this by $(string) you will get html object and before update in database we can use .html() but how we can do this in NodeJs.

<textarea maxlength="20" class="form-control component_label_input" data-component_html="true" data-component_name="attributes" data-component_attribute="script" rows="5">

Any help would be really appreciated.

Thanks in Advance.

3
  • Cheerio provides you a similar functionality inside NodeJS. Commented Feb 22, 2018 at 11:29
  • Not working for me showing $ is not define. Commented Feb 22, 2018 at 11:31
  • what about setAttribute in plain old JavaScript? w3schools.com/jsref/met_element_setattribute.asp Commented Feb 22, 2018 at 11:35

2 Answers 2

3

You can use RegExp:

const sample = '<textarea maxlength="20" class="form-control component_label_input" data-component_html="true" data-component_name="attributes" data-component_attribute="script" rows="5">';

const newString = sample.replace(/maxlength="\d+"/, 'maxlength="' + 50 + '"');

console.log(newString);

To make it a bit more reusable, you can abstract the login into a function:

function updateMaxlength(elementString, newLength) {
    return elementString.replace(/maxlength="\d+"/, `maxlength="${newLength}"`);
}

const sample = '<textarea maxlength="20" class="form-control component_label_input" data-component_html="true" data-component_name="attributes" data-component_attribute="script" rows="5">';

const newString = updateMaxlength(sample, 50);

console.log(newString);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Buddy I was thinking the same
0
const str = '<textarea maxlength="20" class="form-control component_label_input" data-component_html="true" data-component_name="attributes" data-component_attribute="script" rows="5">';

const newLength = 100;//or whatever value you want

str = str.replace(/maxlength="[^"]*"/, `maxlength="${newLength}"`);

1 Comment

It's a good practice to explain your code instead of code dumping.

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.