Regex dont find if inside element? - javascript

I think I need a regular expression (javascript) that can only find a string if it is NOT inside an element. IE if I wanted to find the string "Hello" but not in the div "popup"
<div class="popup">optional content Hello world and more</div>
--No Match--
<div>This is more content Hello and welcome</div>
--Match--
Can someone point me in right direction, negative lookahead?
ok should mention how im getting it :) The find already has a reg ex to "hopefully" ignore searching inside html tags but this needs to work on top of it.
var find = "((?![^<]*>) " + data[i].GlossaryWord.trim() + " )";
var replace = " <a class=\"gobig tooltip\" " + "title=\"" + data[i].GlossaryDescription + "\">" + data[i].GlossaryWord.trim().toLowerCase() + "</a> ";
var elementContent = elementContent.replace(new RegExp(find, 'gi'), replace);

Maybe easier to use CSS selectors. Something like:
document.body.querySelectorAll('div:not(.classy)')

Related

Regular expression to convert html class to attribute

Is there any way to use regular expression alone or with help of javascript to do the following
from
<div class="type-c red blue">
to
<div type="c" class="red blue">
This isn't the solution. Just offers some insights on text parsing this problem without regex. As the OP did mention a possible non-regex solution. Also this answer was posted during a very long comment session, and as such requirements changed.
This solution (in like fashion of #DakotaMethvin's) also attempts to solve it without regex, and as well, resides on a more exact pattern match with class="type-. As such the following code will indeed break (logically) if that's not the match.
However in light of FanCheung's more recent comment [type-x] not always the first class entry, I'm only posting this answer because I already started on posting it.
function replaceIt( s, sentinel ) {
// sentinel: e.g. class="type-
if (sentinel) {
}
else sentinel = 'class="type-';
return s.replaceAll(sentinel , function( match, offset ) {
// get the position of the whitespace after "type-c"
nextSpace = s.indexOf(" ", offset);
// extract the "type" up until and excluding the "next space"
typeVar = s.substring( offset + sentinel.length, nextSpace);
// get the position of the 2nd double quote char
nextDoubleQuote = s.indexOf("\"", nextSpace);
// extract the new "class" names e.g. red blue
newClass = s.substring( nextSpace + 1, nextDoubleQuote);
// create the replacement string. Also something must be done with the leftover chars; prepend them with 'data-source'.
replacement = 'type="' + typeVar + '" class="' + newClass +'" data-source="';
// debugging code
console.log( match + ": " + offset + ": " + typeVar + ": " + newClass);
return replacement;
});
}
console.log( replaceIt( '<div class="type-c red blue">') );
But as noted on recent developments on what I noted on The entire before "class" string will have to be tokenized. So this solution only works if "type-" is the 1st class.
You don't even need regular expressions.
(Okay, you do, but only to find the x value in type-x. Proof here.)
You can use a mix of attribute selectors, the data-* attribute standard, and the Element.setAttribute() method.
Here's an example.
function doChange() {
// Find all divs with a 'type-x' class
let myDivs = document.querySelectorAll('div[class*="type-"]');
myDivs.forEach(curDiv => {
// Get the specific 'x' for the type
let curType = /(?<=type-)[A-Za-z\-]+/.exec(curDiv.classList.toString())[0];
// Set the 'data-type' attribute
curDiv.setAttribute('data-type', curType);
// Remove the 'type-x' class
curDiv.classList.toggle('type-' + curType);
// Write the 'classList' and 'data-type' attributes for show
curDiv.innerText = 'classList: ' + curDiv.classList
+ '; data-type: ' + curDiv.getAttribute('data-type') + ';';
});
}
<div class="type-a red blue">classList: type-a red blue; data-type: undefined;</div>
<div class="red type-b blue">classList: red type-b blue; data-type: undefined;</div>
<div class="red blue type-c">classList: red blue type-c; data-type: undefined;</div>
<button onclick="doChange()">Click Me</button>
This regular expression will match what you describe, regardless of the position of "type-xxx" in class attribute
/class="([^"]*)type-(\w+)([^"]*)"/g
Combining with a string replace
let value = '<div class="type-a b">test</div><div class="a type-b">test 2</div>';
value.replace(/class="([^"]*)type-(\w+)([^"]*)"/g, 'type="$2" class="$1$3"');
this will yield the result
<div type="a" class="b">test</div><div type="b" class="a">test 2</div>

Can't insert line break in Ajax outputString

I have an Ajax script that outputs both the title and description of certain jobs based on user input. While I can get these displaying without issue, I can't seem to insert a line break between the title and description. I have the following:
outputString = savedData[i].firstName + ". Description: " + savedData[i].cardNumber;
var paragraph = $("<p />", {
text: outputString
});
$("#data").append(paragraph);
I have tried inserting a traditional br line break, as well as, \n and \r\n both in the quotation marks before description which just displays the text of the line break rather than breaking the line, and also outside of the quotation marks which breaks any output. How can I successfully implement a linebreak?
Cheers.
As you are providing the outputString string as text, the html <br/> is being displayed as text in the string. You should specify it in as html and use <br/> for line break:
outputString = dataJobs[i].title + ". <br/>Description: " + dataJobs[i].description;
var paragraph = $("<p />", {
html: outputString
});
$("#data").append(paragraph);
If you would like to add a <br/> specifically, then you can do the following:
// assuming that your dataJobs[i].title and dataJobs[i].description are defined
var paragraph = $("<p />");
paragraph
.append(dataJobs[i].title + '.')
.append('<br />')
.append("Description: " + dataJobs[i].description);
$("#data").append(paragraph);
You need to add a <br/> in a separate append call, but not as part of a string. Hope this helps.
In the code below as the P tag has display property set to block by default, so there is no need for using line break.
Setting Title and Description in two different P tags that will solve your problem
Try the following code.
outputString = "<p>Title: "+dataJobs[i].title+"</p><p>description: "+dataJobs[i].description+"</p>";
$("#data").append(outputString);
I think the "jQuery way" should look like this:
var $outputString = $( "<span>" + dataJobs[i].title + ".<br>Description: " + dataJobs[i].description + "</span>" );
$( "#data" ).append($outputString.wrap( "<p></p>" ));
outputString = dataJobs[i].title + ". Description: " + dataJobs[i].description + "<br/>";

JavaScript appendChild text node doesn't break line

a JavaScript n00b here...
I'm generating some html code in javascript, that is going to be displayed as code via the prism HTML markup plugin. The code is dynamically added to a <pre> tag on a button click.
My javascript code is as below. It is the text in line 2, where I need a line break. I have tried /n but that doesn't work it just makes a space.
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
Below is the text string I'm trying to create, where a line break is made where the text LINEBREAK HERE is.
<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>
Is it something like this you are looking for?
By using String.fromCharCode(10) you can insert a line break and with the pre tag (or div having white-space: pre-wrap) the line break will be visible/shown.
var elementNameFinal = "elementname", fieldNameFinal = "fieldname";
var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>" + String.fromCharCode(10) + "<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('#field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);
<pre id="dropdown-code"></pre>
Side note
You can of course use a div as well, having the CSS rule Niet the Dark Absol suggested.
<div id="dropdown-code"></div>
#dropdown-code {
white-space: pre-wrap;
}
Add white-space: pre-wrap to the container's CSS.
After all, if you type a newline in your HTML source, do you get a blank line in the result? Nope. Not without making whitespace significant through CSS.

Add a "new line" in innerHTML

I am trying to create a table with images in first cell and information about the pic in second cell.
I need to add different information in one cell, like that:
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
Is it possible to add a "new line" there?
I mean like that:
cellTwo.innerHTML = arr_title[element] + "/n" + arr_tags[element];
The simplest way is by adding a line break as html
cellTwo.innerHTML = arr_title[element] + "<br />" + arr_tags[element];
If you want your newlines to be treated literally, you could use the <pre> tag
cellTwo.innerHTML =
"<pre>" + arr_title[element] + "\n" + arr_tags[element] + "</pre>";
To round out your understanding:
Since it is html (innerHTML) it renders html and you can use any html you wish, so in this case simply add an good old fashioned <br>:
var test = document.getElementById('someElementId');
test.innerHTML = "The answer <br>to life, the universe, and everything...<br> is 42.";
If it were a string, such as in an alert box or text box etc. then /n would be correct:
alert('Never /n Forget your towel.');
Happy Coding!
- $cr1ptN!nj#
No, <br /> does not work in asp .net but you can instead write it like so
cellTwo.innerHTML = arr_title[element] + arr_tags[element]; arr_title[element] + "/n" + arr_tags[element];
Edit - alternative wrapped in code tags
cellTwo.innerHTML = arr_title[element] + arr_tags[element];
cellTwo.innerHTML += arr_title[element] + "/n" + arr_tags[element];
Semicolon ";" seems to act as line breaks
Remember the "+=" to assign multiple values to the string

How do you document.writeln() a hyperlink?

Very simply question I can't seem to find solved here.
How can I use javascript to print a hyperlink? I'm very beginner with JavaScript and I need something like the following to work:
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");
1) Escape the internal quotes by adding a backslash:
document.writeln("<a href=\"javascript:toggleDummy1();\">" +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
OR
2) Use single quotes:
document.writeln('<a href="javascript:toggleDummy1();">' +
flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
Double quotes " are conflicting. Use a single quote in outermost, and double quotes to wrap href attribute.
So it may look like:
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '')
You need to adjust quotes and double quotes so they doesn't conflict.
However, document.write and the like are very poor practice. You will learn soon enough that you need to append in a container rather than "brute print" into a document.
For example:
var a = document.createElement("a");
a.href = "javascript:toggleDummy1();";
// a more semantic way could be:
//
// a.onclick=function(event){
// toggleDummy1();
// }
//
a.innerText = flaggedKCSarticles.flag_object[i].feedback_text;
document.body.appendChild(a);
There is a problem in your markup, try this
document.writeln("" + flaggedKCSarticles.flag_object[i].feedback_text + "");
or
document.writeln("<a href='javascript:toggleDummy1();'>" + flaggedKCSarticles.flag_object[i].feedback_text + "</a>");
change your syntax like that,
document.writeln('' + flaggedKCSarticles.flag_object[i].feedback_text + '');
i hope this will work

Categories

Resources