3
\$\begingroup\$

In a portion of my code to get a "report view" where the element is different (textarea becomes a div or span) and use the same data with newlines I replace the new lines with page breaks.

Currently the function I use:

$.each($('[id^="mytext-text"]'),(i,e)=>{$(e).html($(e).html().replace(/\n/gm,'<br>'))})

I often find myself using this same format for replacing other things, i.e.,

$(e).text($(e).text+'more text');

Is there a better way (either about using line breaks or about the .text(.text())? I've seen suggestions to simply write your own function but I feel like that doesn't solve the generalized problem.

\$\endgroup\$
  • 2
    \$\begingroup\$ The argument to .text() and .html() can be a function. It receives the old text/html as an argument, and returns the replacement. You don't need .each(), since it automatically loops, and calls the function for each element. \$\endgroup\$ – Barmar Jul 5 '17 at 20:17
  • \$\begingroup\$ Oh jeez I guess it pays to read the documentation once in a while; but I wouldn't have guessed I could apply a selector to each of the texts independently like you suggested without each. So this just becomes $('[id^="mytext-text"]').text((i,e)=>e.replace(/\n/gm,'<br>')) ! \$\endgroup\$ – Cody G Jul 5 '17 at 20:26
  • \$\begingroup\$ It should be (e) =>. The first argument is the old text. \$\endgroup\$ – Barmar Jul 5 '17 at 20:31
  • \$\begingroup\$ api.jquery.com/text/#text-function but it's not D: ! \$\endgroup\$ – Cody G Jul 5 '17 at 20:35
  • \$\begingroup\$ Oops, I misremembered. \$\endgroup\$ – Barmar Jul 5 '17 at 20:37
1
\$\begingroup\$

As Barmar explained in his comment, you can use the function as argument to text() and html(). These methods iterate over all the elements matched by selector so, there is no need of each.

Also, m-multiline flag is not required in the regex and can be removed.

Final Code:

$('[id^="mytext-text"]').html((index, html) => html.replace(/\n/g, '<br />'));
\$\endgroup\$
1
\$\begingroup\$

You could write a jQuery function that takes the method name and a function something like this completely unverified code:

jQuery.fn.replace = function replace(methodName, replacerFunc) {
  return this.each(function() { 
    var $this = $(this);
    var originalValue = $this[methodName]();
    var newValue      = replacerFunc( originalValue);
    $this[methodName]( newValue ); 
  }
}

And then calling it something like:

$('my-selector').replace('html', (v) => v.replace(/\n/gm,'<br>') );
$('my-selector').replace('text', (v) => v + 'more text' );
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.