replace string using regex - javascript

I have text inside "textarea" and I was trying to remove the text between: <textarea></textarea> using replace function with some regex. here is what I did so far:
x = '<TEXTAREA style="DISPLAY: none" id=test name=test>teeeeessst!##$%&*(LKJHGFDMNBVCX</TEXTAREA>';
x.replace('/<TEXTAREA style="DISPLAY: none" id=test name=test>.*</TEXTAREA>/s','<TEXTAREA style="DISPLAY: none" id=test name=test></TEXTAREA>');

You'll probably want something like this:
x.replace(/(<textarea[^>]*>)[^<]+(<\/textarea>)/img, '$1$2');
This will replace things case-insensitively within multi-line strings and avoiding greedy matches of things like ".*"

First problem is that you've got your regex inside quotes. It should just be /regex/ without quotes. Then you're going to have to put a backslash before the forward slash in the regex.
/<TEXTAREA style="DISPLAY: none" id=test name=test>.*<\/TEXTAREA>/
There's no regex flag "s", so I don't know what you thought it means but just drop it.

Similar to Eric's method, or use more general regexp.
var re =/(\<[^<]+\>)[^<]+(<\/[^<]+>)/;
x = x.replace(re, '$1$2');
You can use this tool to have a test. The result should be output to testarea.

Related

regular expression repeating

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>

Regex end in backslash

I'm using regex in javascript to validate a form. One of the form fields is a filepath so needs to end in a backslash.
Specifically, I'm using <input type="text" pattern="" /> and I want to fill out the Pattern attribute to validate it.
Now..
I understand you make a backslash literal by doubling up ie. \\
and I understand that you use the dollar ($) sign to find the end of the string.
So can anyone explain to me why $// and //$ don't work? And maybe give me an example of something that would work?
Thanks
I got it working if I match the entire input, like so .*\\$
Dropping the $ behaved ok too,
<form>
path: <input type="text" pattern=".*\\" title="ends in \">
</form>
(using Chrome 27)
You seem to be mixing up slash / with backslash \. A \\$ is different from a //$, and \\$ should work.

RegEx in javascript. Allow only letters, comma and punctuation

I try to make a RegEx for validating a form in javascript. The RegEx should only allow letters comma and punctuation. For instance I have this string:
Hi, this is a test of RegEx. Does it work
I've tried the following
/^[A-Za-z0-9,. ]{3,50}$/;
But it doesn't seems to work. Solutions?
Thanks!
EDIT:
This is my code:
<script type="text/javascript">
var RE_SSN = /^[A-Za-z0-9,. ]{3,50}$/;
function checkSsn(ssn){
if (RE_SSN.test(ssn)) {
alert("OK");
javascript:addAppointment(document.forms[0])
} else {
alert("NO!");
}
}
</script>
<div id="r">
<label for="receipt">Receipt</label><input type="checkbox" name="receipt" value="1"/>
</div>
<input type="button" value="Post it" onclick="checkSsn(this.form.content.value);"/>
You might need to escape the "." as that is a special character in regex.
/^[A-Za-z0-9,\. ]{3,50}$/;
Actually probably not. Try using http://www.regextester.com/ - I was able to get it to work anyway. Can you show us the full code for how you're implementing this?
if you want no punctuation at the beginning of the field:
/^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/
this also allows spaces (one scenario for this is last name - De La Hoya, or O'Doul)

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>

How can I use a multiline value for an HTML tag attribute? (i.e. how do I escape newline?)

How do I include a newline in an HTML tag attribute?
For example:
<a href="somepage.html" onclick="javascript: foo('This is a multiline string.
This is the part after the newline.')">some link</a>
Edit: Sorry, bad example, what if the tag happened to not be in javascript, say:
<sometag someattr="This is a multiline string.
This is the part after the newline." />
Edit 2: Turns out the newline in the string wasn't my problem, it was the javascript function I was calling. FWIW, "
" can be used for newline in an HTML attribute.
From what I remember about the HTML standard, character entities work in attributes, so this might work:
<sometag someattr="This is a multiline string.
This is the part after the newline." />
I'm not sure if the "newline" you want ought to be
(\n) or
(\r\n), and I'm not sure if browsers will interpret it the way you want.
Why do you need it? What specific problem are you trying to solve by adding a newline in an HTML tag attribute?
To include a multiline value, just continue the text of the html attribute on the next line in your editor e.g.
<input type="submit" value="hallo
hallo">
will put the second hallo under the first
As a general rule newlines in attributes are preserved so your second example would work fine. Did you try it? Can you give a specific example where you are having problems with it?
As test take a look at this:-
<a href="somepage3.html" onclick="javascript: alert(this.getAttribute('thing'))" thing="This is a multiline string.
This is the part after the newline.">some link</a>
The alert include the newline in the attribute.
<a href="somepage.html" onclick="javascript: foo('This is a multiline string. \
This is the part after the newline.')">some link</a>
Javascript needs a backslash at the end of the new line in a string.
i'm not certain, but you can try \r or \n
javascript: foo('This is a multiline string.\rThis is the part after the newline.')
or
javascript: foo('This is a multiline string.\nThis is the part after the newline.')
Usually, line breaks in HTML source code display what you intended in the result.
(Depends on the editor of course)
Since it's in Javascript, you would use "\n" if inside double-quotes (not positive about single-quotes, I've been in PHP a lot lately.
Honestly, it's worth mentioning that you should use Events and a delegator instead of placing a javascript event directly on the element.

Categories

Resources