Regular Expression matches similar strings - javascript

I am trying to alter classnames for a module via jquery and right now I have this RegEx
/module-\w+/gi
Used in this fashion
//// Removes all module-xxxx classes
var classes = $target[0].className.replace(/module-\w+/gi, '');
This has worked fine until now however I have to alter the structure of my module class so that it resembles this
<div class="module">
<div class="module-header">
<div class="module-header-content module-blue ..."></div>
</div>
<div class="module-content"></div>
</div>
The ... just means there could be other class names.
I need to change the RegEx so that it matches only module-blue (could be module-default, module-green, module-whatever, but always in the format of module-COLORNAME) and not doesn't match module-header-content as well.
The jquery selects the classname of: module-header-content module-blue

var classes = $target[0].className.replace(/\bmodule-\w+(?!-)\b/gi, '');
With word boundaries, the expression has to match an entire group of module- followed by at least one letter that is not followed by a dash.
http://jsfiddle.net/ExplosionPIlls/WqbKJ/

Related

Contenteditable regex whitespace not working

I am trying to validate if the contenteditiable value has only whitespace/blank space. In my example if the value have only whitespace/blank space it should not match according to my regex string, but it not working as intended. It keeps matching when I enter complete blank spaces.
edit: the black space is where you can enter text.
https://jsfiddle.net/j1kcer26/5/
JS
var checkTitle = function() {
var titleinput = document.getElementById("artwork-title").innerHTML;
var titleRegexp = new RegExp("^(?!\s*$).+"); //no blank spaces allowed
if (!titleRegexp.test(titleinput)) {
$('.start').removeClass('active-upload-btn');
console.log('no match')
} else if (titleRegexp.test(titleinput)) {
$('.start').addClass('active-upload-btn');
console.log('match')
}
};
$('#artwork-title').on('keyup change input', function() {
checkTitle();
});
HTML
<div class="post-title-header">
<span class="user-title-input title-contenteditable maxlength-contenteditable" placeholder="enter text here" contenteditable="true" name="artwork-title" id="artwork-title" autocomplete="off" type="text" spellcheck="false">
</span>
</div>
<div class="start">
turn red if match
</div>
If you look at the actual inner HTML, you'll see things like <br> elements or entities. Your regex doesn't look equipped to handle these.
You may want to consider using textContent instead of innerHTML if you just care about the text, not the HTML. Or alternatively, if you really want plain text, use a <textarea/> instead of a content-editable div, which is for rich-text-style editing that produces HTML.
Edit:
Your regex is not quite right either. Because you're using the RegExp constructor with new RegExp("^(?!\s*$).+"), the \s in your string literal is going to turn into a plain s; you have to use a \\s if you want the regex to have an actual \s in it. IMO, it's always better to use a regexp literal unless you're building one dynamically, like /^(?!\s*$).+/, or I find this to be a simpler alternative to tell you if a string is entirely whitespace: /^\s+$/.

Recognize character inside div and add class javascript

I am trying to recognize character inside div and add to all the matches class.
Example :
> Kapetown > China Town >London > Washington
I want to recognize the character > and give all of them class
I tried to do this
if (sign.indexOf("$") >= 0) {
//remove the sign
}
Here is a trick you can use:
var a = '> Kapetown > China Town >London > Washington' //get the text from document here
a = a.split('>');
a = a.join('<span class="myClass">></span>');
Now you can replace "a" in your document.
This is just a trick you can use in your case. Maybe this will help you.
I assume that there is only text inside the targeted div
$(document).ready(function() {
// get the target element
var breadcrumbs = $('#breadcrumbs')
// get all text of that element. Note: this will remove all
// HTML tag and get only the text
var str = breadcrumbs.text()
// a regEx to find all occurrences of ">" sign
// and wrap them with span.myClass
var strHtml = str.replace(/\>/g, "<span class='myClass'>></span>");
// push the replaced string back to the targeted element
breadcrumbs.html(strHtml)
})
.myClass {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<div id="breadcrumbs">> Kapetown > China Town >London > Washington</div>
If I understand your problem correctly, then you have a particular HTML like so:
<div id="abc">
> Capetown > China > London > Washington
</div>
and you want it to be lets say something like this:
<div id="abc">
<span class="some-class">></span> Capetown <span class="some-class">></span> China <span class="some-class">></span> London <span class="some-class">></span> Washington
</div>
Then by vanilla javascript you could achieve this via Regex. Here is how I would do it if the HTML was like the example I proposed:
let content = document.getElementById('abc').textContent.replace(/>/g, '<span class="some-class">></span>');
document.getElementById('abc').innerHTML = content;
What I am doing here is that with document.getElementById('abc').textContent, I am getting the text content that is inside <div id="abc">...</div> and I am storing this text content in a mutable variable content.
Then I used the String.prototype.replace method of JavaScript to replace the required character (in our case it is the ">" character). The String.prototype.replace method accepts two parameters: a pattern and the replacement string. read about the replace method here
The character I want to select is ">". So using Regex the pattern I want to match is />/. Now just using this expression will only match the first instance of ">". So I give it a global parameter to match all occurrences of ">" by />/g.
Now we want to give it a class. So I decide to use the inline HTML element <span> to avoid any changes in the DOM layout. Now for the replacement substring, I use <span class="some-class">></span>. The > is the HTML code for the ">" sign. Lets include these two parameters in our String.prototype.replace method as content.replace(/>/g, '<span class="some-class">></span>');
When executed, the variable content now contains our required character with a class. Next, I replaced the content of <div id="abc">...</div> by the content variable with document.getElementById('abc').innerHTML = content;. I used the .innerHTML property because we have included some HTML in our replacement string.
If this is what you wanted then hope this helps.
use can use {'>'} for react
example:
<div className='row'>
{route[0]} {'>'} {route[1]} {'>'} {route[2]}
</div>
where route = ["home","products","productID"];

Jquery replace character and apply classes

I have several string in the following format
<span class="label">20€</span>
And want to convert it all to something like this:
<span class="label">20<small>€</small></span>
How could I achieve this in Jquery?
I'd suggest:
$('.label').html(function(i,h){
return h.replace(/([^\d+])/,'<span class="small">$1</span>');
});
JS Fiddle demo.
Bearing in mind that I'm choosing to use span with a class of small, rather than a small element.
Under HTML 5, though, remember that the small element is:
repurposed to represent side-comments and small print, including copyright and legal text, independent of its styled presentation.
Source: https://developer.mozilla.org/en-US/docs/HTML/Element/small.
If the currency symbol is predictable, you could explicitly replace the € character (rather than using the above to replace, essentially, 'not-numbers'):
$('.label').html(function(i,h){
return h.replace(/(€)/,'<span class="small">$1</span>');
});​
JS Fiddle demo.
Or, assuming the currency symbols are known in advance, you could specify the symbols to be replaced (using regular expressions again, though):
$('.label').html(function(i,h){
return h.replace(/([€£$])/,'<span class="small">$1</span>');
});​
JS Fiddle demo.
References:
html().
Regular expressions.
String.replace().
It works, but is affecting other strings that doesn't have the €
character. I mean other spans with the same class, it changes the
first letter or those strings. Figure I have other strings with this
syntax: <span class="label">request price</span>
HTML:
<span class="label currency">20€</span>
Note 1: Added additional class currency to identify the span that needs to be modified.
Note 2: Use a span instead of small as all styles elements are re purposed. (Thanks #David). Read more info #MDN https://developer.mozilla.org/en-US/docs/HTML/Element/small
You can use replace function like below,
$(function () {
$('span.label.currency').html(function(i, v) {
return v.replace('€', '<small>€</small>');
});
});

Javascript regex not working as intended

I have the HTML from a page in a variable as just plain text. Now I need to remove some parts of the text. This is a part of the HTML that I need to change:
<div class="post"><a name="6188729"></a>
<div class="igmline small" style="height: 20px; padding-top: 1px;">
<span class="postheader_left">
RuneRifle
op 24.08.2012 om 21:41 uur
</span>
<span class="postheader_right">
Citaat Bewerken
</span>
<div style="clear:both;"></div>
</div>
<div class="text">Testforum</div>
<!-- Begin Thank -->
<!-- Thank End -->
</div>
These replaces work:
pageData = pageData.replace(/href=\".*?\"/g, "href=\"#\"");
pageData = pageData.replace(/target=\".*?\"/g, "");
But this replace does not work at all:
pageData = pageData.replace(
/<span class=\"postheader_right\">(.*?)<\/span>/g, "");
I need to remove every span with the class postheader_right and everything in it, but it just doesn't work. My knowledge of regex isn't that great so I'd appreciate if you would tell me how you came to your answer and a small explanation of how it works.
The dot doesn't match newlines. Use [\s\S] instead of the dot as it will match all whitespace characters or non-whitespace characters (i.e., anything).
As Mike Samuel says regular expressions are not really the best way to go given the complexity allowed in HTML (e.g., if say there is a line break after <a), especially if you have to look for attributes which may occur in different orders, but that's the way you can do it to match the case in your example HTML.
I need to remove every span with the class postheader_right and everything in it, but it just doesn't work.
Don't use regular expressions to find the spans. Using regular expressions to parse HTML: why not?
var allSpans = document.getElementsByClassName('span');
for (var i = allSpans.length; --i >= 0;) {
var span = allSpans[i];
if (/\bpostheader_right\b/.test(span.className)) {
span.parentNode.removeChild(span);
}
}
should do it.
If you only need to work on newer browsers then getElementsByClassName makes it even easier:
Find all div elements that have a class of 'test'
var tests = Array.filter( document.getElementsByClassName('test'), function(elem){
return elem.nodeName == 'DIV';
});

How to check what is after hyphen with jQuery's "Attribute Contains Prefix Selector"

I've got some html like:
<a class="link" href="#>link</a>
<a class="link-0" href="#>link</a>
<a class="link-1 enabled" href="#>link</a>
<a class="link-2" href="#>link</a>
I can select all of those links by:
$('[class|="link"]');
but I find it very difficult to check what is after hyphen, I think about getting classes by attr('class') splitting with split(' ') and checking each class, if it starts with "link" and splitting again with split('-').
Anyone knows better way to do this?
You can use a regular expression:
var matches = element.attr("class").match(/^link-?(\d*)$/);
var whichLink = matches[1];
Interesting that other variations of this selector doesn't match it - perhaps a bug with jquery with hyphens.
$('a[class^="link-"]')
Turns out others work to, just not "word selectors"
$('a[class*="link-"]')

Categories