regular expression repeating - javascript

I'm trying to add 'ig' in the middle of each syllable in a word. For example, super (su and per) would become sigupiger (sigu and piger) Here is my code so far:
function iggify(text) {
var iggEdText = text.split(/((a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$)/ig).join("ig");
document.getElementById('resultField').innerHTML = iggEdText;
}
Demo codepen
My regular expression repeats twice after joining. e.g. words becomes wigoigoigrds, instead of simply wigords.
How can I make it only repeat once?

Instead of splitting an joining, you just need to append ig to the vowels that can be easily achieved with .replace():
text.replace(/(?:a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$/ig, "ig$&");
// ^^^ - Non-capturing group ^^ - The whole matched text
I removed the outer capturing group and changed the second one to non-capturing. Since we replace with the whole match, I use the $& back-reference in the replacement part (i.e. I restore the matched text during replacement and add ig before it).
See the whole snippet below:
function iggify(text) {
var iggEdText = text.replace(/(?:a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$/ig, "ig$&");
document.getElementById('resultField').innerHTML = iggEdText;
}
<h1>
Convert words to wig-ords!
</h1>
<div>
<input id="inputBox" placeholder="Type words to iggify here">
</div>
<div>
<button id="searchButton" onclick='iggify(document.getElementById("inputBox").value)'>Iggify!</button>
<span id="resultField"></span>
</div>
</body>

Related

JavaScript replace with an exception string

I have the following html tag (which is custom):
<meltdown-code data-lang="HTML">
<span><br>
<p>Hi</p><br>
</span><br>
</meltdown-code>
Simple enough. Now, I'm trying to make the HTML tags show as plain text, instead of being rendered as a separate element. To do that, I am replacing all the < with <, and all the > with >
tagHTML.replace(/</g, '<')
The problem: This also replaces the <br> tags, which doesn't create a new line. Here is the solution, in a perfect world:
tagHTML.replace(/</g, '<', {exceptions: '<br>'})
Obviously, that's not how it works. Any help is appreciated.
Thanks!
Negative lookahead for <br> before matching <.
const text = `<meltdown-code data-lang="HTML">
<span><br>
<p>Hi</p><br>
</span><br>
</meltdown-code>`;
const output = text.replace(/(?!<br>)<([^>]+)>/g, '<$1$gt;');
console.log(output);
<code></code>

Removing whitespace in textarea ignored by jQuery.trim()

I have a <textarea> which contains a text called by php. The text contains an ID of the user, so it's for every user different. However, the html looks always like this:
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
How do I remove these whitespaces. I have tried multiple trim suggestions or Regex approaches on SO, but none of them are working. The textarea cannot be changed into a div or p.
Update:
Regex is somehow ignored, but the below answer gave the outcome:
$("#text").val((i, v) => '${v.slice(1, -1).trim()}');
Use regex pattern /\s{2,}/g in .replace() that match multiple spaces and remove them from string.
$("#text").val((i, v) => v.replace(/\s{2,}/g, ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>
Also you can remove " from start and end of string using String.slice() and then remove space using .trim(). At the end wrap string with ""
$("#text").val((i, v) => `"${v.slice(1, -1).trim()}"`);
You can use a regex to remove quotes and spaces
$("#text").val($("#text").val().replace(/^"\s+(.*?)\s+"$/,"$1"));
console.log(">"+$("#text").val()+"<")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="text" readonly="readonly">" example text "</textarea>
</div>

Remove first line from Textarea

I have a tool that removes the blank lines from a confirmation (text) but for some reason there is a top line that is not being read as blank line and does not get deleted.
Currently my tool allows a person to paste text into the textarea then when "remove spaces & copy" button is clicked blank lines are removed and text is copied to the clipboard.
I want to keep the same function but somehow delete the first line either when text is entered into the textarea or when "remove spaces & copy" button is clicked.
<script>
function copyToClipboard(element) {
var text = $(element).clone().find('br').prepend('\r\n').end().text()
element = $('<textarea>').appendTo('body').val(text).select()
document.execCommand('copy')
element.remove()
}
</script>
<textarea name="mas" rows="100" rows="50" contenteditable="true" id="p20" class="content" onchange="this.value=this.value.replace(/[\n\r](?!\w)/gi,'');" style="height: 500px; width:800px;" type="text" data-bind="value: myValue, hasFocus: cleared"></textarea>
<!----------- BUTTONS ------------>
<div class="fixed">
<button onclick="copyToClipboard('#p20')" class="templateBtn">Remove Spaces & Copy</button>
<input type="button" data-bind="click: clearValue" value="clear" class="templateBtn" />
<script type="text/javascript">
var viewModel = {
myValue: ko.observable(''),
cleared: ko.observable(false),
clearValue: function() {
this.myValue('');
this.cleared(true);
}
};
ko.applyBindings(viewModel);
</script>
<!----------- END.BUTTONS ------------>
<div class="mas" id="hide" ></div>
<pre contenteditable="true" id="p20" class="templateText">
</div></div>
The regular expression [\n\r](?!\w) matches any CR or LF not followed by an alphanumeric or underscore character. So it can match the first of two line terminators in a row when replacing blank lines with the null string. '' It doesn't match a line terminator followed by a letter. Hence a line terminator at the beginning of text, followed by a word character, is left in place.
Blank lines defined as "Start of line, followed by zero or more whitespace characters not including line terminators, followed by end of line, followed by zero or more line terminators" can be matched by a multi line regular expression such as:
/^[ \f\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$[\n\r]*/gm;
where the first character set is that used for matching whitespace (\s) after removing the line feed and carriage return characters, and the $[\n\r]* component matches both line terminators and end of input. (Edited: a trailing blank line without a line terminator at the end is matched)
Try it below by entering lines and clicking outside the textarea element to trigger a change event:
function removeBlankLines( textArea) {
var blankLine = /^[ \f\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]*$[\n\r]*/gm;
textArea.value=textArea.value.replace(blankLine,'');
}
<textarea onchange="removeBlankLines( this)" cols="20" rows="8"></textarea>
This does not trim or remove spaces within non-blank lines. If you are still having trouble achieving what you wish to do, please update the question with text data used to produce the problem and detailed description of what you expected and what you got. Please remove the knockout code if it not related to the question (it doesn't appear to be).
Here is a quick fix you could use, perform a trim() on the replaced text:
<textarea name="mas" rows="100" rows="50" contenteditable="true"
id="p20" class="content"
onchange="this.value=(this.value.replace(/[\n\r](?!\w)/gi,'')).trim();"
style="height: 500px; width:800px;" type="text"
data-bind="value: myValue, hasFocus: cleared"></textarea>

highlight text contained in multiple adjacent elements

I am building a JavaScript search application that takes a text string and breaks it into multiple parts using spans. A separate function will search either on the entire text or only in one of the previously identified sections.
My problem is that when I attempt to highlight the text after I identify the sections. I can't figure out how to highlight the text contained in multiple spans.
For example if I have the string.
<div id="container">
<span id="sectionOne">This is my first section</span>
and
<span id="sectionTwo">This is my second section</span>
</div>
how would I highlight section and This which is contained in both spans as well as a text element?
Thanks for any help. If it is possible to do this in pure JavaScript that would be most helpful; although, any solution is greatly appreciated.
<input type="text" id="search" />
<div id="container"> <span id="sectionOne">This is my first section</span> <span id="sectionTwo">This is my second section</span>
</div>
<div id="output"></div>
JS
$('#search').keyup(function () {
var self = $(this);
var src_str = $("#container").html();
var term = $('#search').val();
term = term.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("(" + term + ")", "gi");
src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1</mark>$2<mark>$4");
$("#output").html(src_str);
});
Fiddle
I managed to get something to work by parsing the string and storing the various parts in a object with the position values. When I want to search on an individual section I simply search within my object then replace the correct part of the original input.
I am sure there is a better way to solve the problem but breaking up the string into an internal object was the only way I could get this to work.

how to remove trailing html break from string?

I have a string below and I want to remove the trailing but I'm struggling. Any help?
This is a string<br>
next line<br>
So after my function, the string should be
This is a string<br>
next line
Doing this code below doesn't seem to be working. Well, it works but it doesn't clear out two trailing breaks.
mystring=mystring.replace(/<br>$/,'');
So if my string is actually:
This is a string<br>
next line<br>
<br>
then the code above just returns
This is a string<br>
next line
<br>
If you want to remove all trailing <br>s, then use a quantifier:
/(<br>\s*)+$/
\s matches any white space characters, so even if there is line break between continuous <br>s, it will still match.
DEMO
If it's the contents of an HTML element, you can just use jQuery to remove the element:
$('#container').children('br').last().remove();
If it's a string, you can do something like this (still leveraging jQuery):
var cleaner = $('<div />').html(mystring);
cleaner.children('br:last-child').remove();
mystring = cleaner.html();
I prefer this over splitting on a string or your current RegEx because you're not handling the scenario of a BR tag like this: <br />.
http://jsfiddle.net/TTg3p/
I tested your code, and it seems to work. I pasted the following into a file and then viewed in firefox, and clicked view source. The second br was not visible in the source.
<html>
<body>
<script>
var mystring = 'This is a string<br>\n next line<br>'
mystring=mystring.replace(/<br>$/,'');
document.write(mystring);
</script>
</html>
Perhaps your mystring variable has an actual linebreak (\n) at the end of it after the br, so your regular expression is not matching?
Try this:
mystring.split('<br>').slice(0,-1).join('<br>');
demo
:)
If you want to remove the last trailing <br> inside an element, you can use this:
const element = document.getElementById('element')
console.log('Before:', element.innerHTML)
const last = element.childNodes[element.childNodes.length - 1]
if (last.tagName === 'BR') last.remove()
console.log('After:', element.innerHTML)
<div id="element">Some text<br>other text<br></div>

Categories

Resources