I have a javascript code which is supposed to get the content of a div. and then compare to a string and if they are equal change the content on that div.
var strs = document.getElementById('prodAvailable').innerHTML.toLowerCase();
var stra = "GS2023".toLowerCase();
if(stra == strs) {
document.getElementById('prodAvailable').innerHTML = "milk";
}
<div id="prodAvailable" class="Value"> GS2023 </div>
it doesnt work because the string in your div has spaces in the beginning and end of the string. you might want to trim the string prior to comparison.
var strs = document.getElementById('prodAvailable').innerHTML.toLowerCase().trim();
var stra = "GS2023".toLowerCase();
if (stra == strs) {
document.getElementById('prodAvailable').innerHTML = "milk";
}
<div id="prodAvailable" class="Value"> GS2023 </div>
Related
I have a javascript string that contains some code like [Hover on me](Tooltip text). I want to convert this code to HTML. [] containing text and () containing tooltip text
Here is what I want
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
The string contains multiple tooltip codes and I need to convert each of them to this HTML code
what I am trying
<p id="p">blabla [some info](tool) it is text [one](tool) [two] (tool)</p>
var text = document.getElementById('p').innerHTML;
var matches = text.match(/\[(.*?)\]/);
var final = text.match(/\((.*?)\)/);
var res = text.replace(matches[0], "<span>"+matches[1]+"</span>");
var newtext = document.getElementById('p').innerHTML = res;
var ros = newtext.replace(final[0], "<span>"+final[1]+"</span>");
document.getElementById('p').innerHTML = ros;
console.log(ros);
I know the code is pretty messed up but I need some help with this. I was also trying other code as well but that didn't work either, here is fiddle https://jsfiddle.net/mohitchandel/aszv8w93/10/
var text = document.getElementById('p').innerHTML;
// You may want to validate this loop better.
while( text.indexOf(')') > 0 ) {
let a = text.slice( text.indexOf('[') + 1, text.indexOf(']') ),
b = text.slice( text.indexOf('(') + 1, text.indexOf(')') ),
c = `<div class="tooltip">${ a } <span class="tooltiptext">${ b }</span></div>`;
text = text.slice( 0, text.indexOf('[') ) + c + text.slice( text.indexOf(')') + 1 );
}
This could get you started.
--
RMZ
Hi there how can I replace from this to this
var str = document.getElementById('bos').innerHTML.replace('col_nr', "");
document.getElementById('bos').innerHTML = str;
<div id="bos">
col_nr[504]
</div>
I want to be able to take only the number without brackets
You can perform more replace() to achieve your goal, demonstrated as below. Alternatively, you can use regular expression to perform your task as well.
var str = document.getElementById('bos').innerHTML.replace('col_nr[', '').replace(']', '');
document.getElementById('bos').innerHTML = str;
<div id="bos">
col_nr[504]
</div>
You could replace all not number characters.
var element = document.getElementById('bos');
element.innerHTML = element.innerHTML.replace(/\D/g, "");
<div id="bos">
col_nr[504]
</div>
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.
I am having trouble getting the regex to work.
Here is an html line I am working on:
<td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
Now, here is the javascript/jquery that I have at the moment:
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").text(); //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate); //put the new text back
I think I'm pretty close, but I don't have the regex right yet.
The regex ought to replace the firstname with whatever is entered in the textbox for $thisval (method is attached to keyup procedure on textbox).
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.
If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
var between = false;
$("#gentextCodeArea").contents().each(function () {
if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
if (between) return false;
between = true;
} else if (between) {
this.nodeValue = thisval;
thisval = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
What went wrong in your code
By using text() you don't get the comment tags. To get those, you need to use html() instead
replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate
It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.
Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").html(); //fetch the html
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").html(currentTemplate); //put the new text back
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
here is a function which will generate an appropriate Regular expression:
function templatePattern(key) {
return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:
'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
.replace(templatePattern('firstname'), 'Bob')
.replace(templatePattern('lastname'), 'Johnson') // "Bob Johnson"
$(function(){
function onKeyUp(event)
{
if(event.which === 38) // if key press was the up key
{
$('.firstname_placeholder').text($(this).val());
}
}
$('#firstname_input').keyup(onKeyUp);
});
input[type=text]{width:200px}
<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
<tr>
<td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example:
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
<script>
var chars = 55;
if ($('#mytext').text().length > chars){
//add <br> after first dot found after number of chars specified.
}
</script>
... The output would be:
This is just a example. I need to find a solution. I will appreciate any help.<br>
Thank you.
You can try this
var chars = 55;
if ($('#mytext').text().length > chars){
var text = $('#mytext').text(); // div text
var chars_text = text.substring(0, chars); // chars text
var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span
$('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again
}
span{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytext">
This is just a example. I need to find a solution. I will appreciate any help. Thank you.
</div>
Note: if you just need to replace the next one dot after chars you can
use '.' instead of /\./g
this way : With JQUERY Substring
<p>
this is test string with jquery . test 1 2 3 4 45 5 . test test test
</p>
<b></b>
<script>
var a = $('p').text();
var _output = '';
var _allow_index = 40;
if (a.length > _allow_index)
{
var x = a.split('.');
for(var i=0; i<x.length; i++)
{ if (_output.length < _allow_index) { _output+=x[i]+'.'; } }
}
else { _output = a; }
$('b').html(_output + '<br>'+a.substr(_output.length,a.length));
</script>
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages.
Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text().
However here is a way for the given case:
var container = $('#mytext');
var length = 55;
var insert = '<br/>';
var text = container.text().trim(); // text() or html()
var dotPosAfterLength = text.indexOf(".", length);
if (dotPosAfterLength != -1) {
container.html(
text.substring(0, dotPosAfterLength+1)
+insert
+text.substring(dotPosAfterLength+1)
);
}
You just need to add this property in CSS.
<div id="mytext">
This is just a example. I need to find a solution.
I will appreciate any help. Thank you.
</div>
<style>
div#mytext{
word-wrap: break-word;
}
</style>
<div id = "board>
<div>{abc</div>
<div>def</div>
<div>ghi}</div>
</div>
I want compare every char inside the div at their position and do something when if found { or }
Im aware that this is possible by wrapping every char within <span></span>
Is there a way to do this without using a span? I will use this for brace matching of my code editor project. this is what i've done using span wrapping, but it is so slow..
$exceedingInlineDiv = $('#board_code_dup > div').eq(x);
if( $exceedingInlineDiv.text() == ''){
var chars = '<span> <br> </span>';
$exceedingInlineDiv.html(chars);
}
else{
var chars = jQuery.map($exceedingInlineDiv.text().split(''), function(c) {
return '<span>' + c + '</span>';
});
$exceedingInlineDiv.html(chars.join(''));
}//else
I'm not sure what you want to do, but maybe you want something like this:
var board = document.getElementById("board"),
divs = board.getElementsByTagName("div"),
texts = [], i = 0;
for (; i < divs.length; i++)
texts.push(divs[i].innerHTML);
// texts => ["{abc", "def", "ghi}"]