I would like to ask for your help in having a web site that uses the following javascript:
<html>
<head>
...
</head>
<body>
...
<script>
$(document).ready(function(){
var pathArray = window.location.pathname.split( '/' );
var secondLevelLocation = pathArray[0];
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "";
newPathname += pathArray[i];
}
var str = "asd fgh roof_material";
var res = str.match(newPathname);
if (res) {
document.getElementById("demo").innerHTML = res;
} else {
document.getElementById("demo").innerHTML = "Basic text";
}
});
</script>
<div id="demo"></div>
</body>
</html>
Such as my website address is: https://www.mywebsite.com/roof_material
I get a string in a variable (newPathname) which contains the text after the / sign, in this example: roof_material
The problem is:
I would like to find the value of this variable in a text and if you can find it then you can post it on the website. It's works if I put a text in a variable like in the script:
var str = "asd fgh roof_material";
But I would like to find the value of this variable (newPathname) in a separate html file, if it is possible like this:
The newPathname value such as: roof_material
In the separated .html file content:
<div id="protection_material">Line-X material</div>
<div id="roof_material">Roof materials</div>
<div id="pool_material">Swimming pools</div>
In this example I would like to find the roof_material ID in the .html file and get the content of the div: "Roof materials" and I would like to show this text on the page:
<div id="demo">Roof materials</div>
If it has positive match then show the content of the div in other cases, it will print a basic text like in the example: "Basic Text"
Could anyone help to make it happen?
#Terry thanks for your answer!
I think I found a simpler solution, but it's not perfect:
<script>
$(document).ready(function(){
var pathArray = window.location.href.split('=')[1];
var secondLevelLocation = pathArray[0];
var newPathname = "";
for (i = 0; i < pathArray.length; i++) {
newPathname += "";
newPathname += pathArray[i];
}
document.getElementById("demo").innerHTML = newPathname;
});
</script>
<div id="demo">Országosan</div>
If I type it in the browser such as: https://www.mywebsite.com/index then the text that will appear in #demo div is: "Országosan"
It's good, but if I type such as: https://www.mywebsite.com/index?id=Cserkeszőlő
then the result is good but character encoding does not work properly.
The result in the #demo div: Cserkesz%C5%91l%C5%91 , but I would like to show the correct encoded text like this: Cserkeszőlő
Can you give me a solution on this?
Related
I've tried this
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
var mySte = myStr.textContent;
console.log(mySte);
</script>
</body>
and I want this following outcome
just some random text
random text
You can use this regex to find and replace string without breaking html: /(?!<[^>]+)\.(?![^<]+>)/g
[myattr]
{
background-color: pink;
}
[myattr]:after
{
content: "this element's attribute is: " attr(myattr);
background-color: lightgreen;
margin: 1em;
}
p > span
{
background-color: lightblue;
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some. random text. <span myattr="text.with.dots">nested.html</span> end.
<span>i < 40. But i is also > 30. What are valid values of i?</span>
</p>
<button type="button" onclick="strReplace();">Replace</button>
<script>
function strReplace(){
var myStr = document.getElementById("text");
myStr.innerHTML = myStr.innerHTML.replace(/(?!<[^>]+)\.(?![^<]+>)/g, "<br>");
console.log(myStr.innerHTML);
}
</script>
</body>
To directly answer the question:
var outputHtml = inputText.replace(/\./g, '<br />');
The Javascript replace method will by default replace the first instance of something (the first . in this case), so the g regex modifier tells it to replace them all. The \. in the regex is because . is a special character in regexes. This will replace every dot in the text.
What about ellipsis?
This technique won't work well on text that contains literal ellipsis, like this:
Hello world...
If your text is likely to contain this, and you want that to be ignored, then the following regex is more appropriate:
/[^\.](\.)[^\.]/g
This'll match any . which is not surrounded by other .
var outputHtml = inputText.replace(/[^\.](\.)[^\.]/g, '<br />');
Handling HTML
In the question here, the input is actually coming from the DOM. We can't replace . on its innerHTML as it would replace content inside HTML tags as well. So, if your input text is coming from the DOM like this (and not, say, a textarea), then the safest route is to apply the replacement only to text nodes. That is done like this:
document.getElementById("start").addEventListener("click", () => {
var inputNode = document.getElementById("text");
replace(inputNode);
});
function replace(node) {
if(!node) {
return;
}
if (node.nodeName == '#text') {
// We've found a text node. Apply the regex to it now.
// Note that you can use either of the above regexes here.
var inputText = node.textContent;
var lines = inputText.split(/\./g);
if(lines.length > 1) {
// It had at least one dot in it.
// Swap in this new set, each with a <br /> between them.
var parent = node.parentNode;
var nextSibling = node.nextSibling;
parent.removeChild(node);
lines.forEach((line, i) => {
if(i != 0){
// insert the <br>
var br = document.createElement('br');
parent.insertBefore(br, nextSibling);
}
var textNode = document.createTextNode(line);
parent.insertBefore(textNode, nextSibling);
});
}
} else {
// Loop through each child node.
// We go backwards such that completed replacements don't affect the loop.
for(var i=node.childNodes.length - 1; i>=0; i--) {
replace(node.childNodes[i]);
}
}
}
<html>
<head>
<title>None</title>
</head>
<body>
<p id="text">just some random text. random text</p>
<button type="button" id="start">Replace</button>
</body>
</html>
If you're starting from a HTML string inside a browser, you can then use the above replace method and the browsers internal parsing to safely only affect the actual text:
function replaceHtmlString(html) {
var div = document.createElement('div');
div.innerHTML = html;
replace(div);
return div.innerHTML;
}
I've got a product title which I'm splitting and inserting a linebreak using javascript like this:
<script>
function myFunction() {
var str = "How are you - doing today?";
var res = str.split("-").join('<br>');
document.getElementById("demo").innerHTML = res;
}
</script>
This works for most case scenarios, however in some cases I will need to remove the second line completely. So everything after the - will need to be removed. Only within that element though, so if I've got this for example
<h3>This is a product - title</h3>
the result should be
<h3>This is a product</h3>
Again this only needs to apply to elements with a certain class. Anybody got any idea ow to do this?
Why not us a simple replace,
string = string.replace(/-/g, '<br>');
or for complete deletion, take
string = string.replace(/-.*$/g, '');
Check className of the element:
function myFunction() {
const str = `How are you - doing today?`
const first = str.split(`-`)[0]
const all = str.split(`-`).join(`<br/>`)
const el = document.getElementById(`demo`)
const el.innerHTML = el.className === `any-name` ? first : all
}
Try this:
(function() {
// For splitted titles
var split = document.querySelectorAll(".dash-split");
var splits = [];
split.forEach(function(spl) {
splits.push(spl.innerHTML.split("-").join("<br>"));
});
console.log(splits); // Outputs ["This is <br> split!"]
// For removed titles
var removedEls = document.querySelectorAll(".dash-split");
var removed = [];
removedEls.forEach(function(rem) {
removed.push(rem.innerText.split("-")[0].trim());
});
console.log(removed); // Outputs ["This is"]
})();
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<div>
<h1 class="dash-split">This is - split!</h1>
<h1 class="dash-remove">This is - removed!</h1>
</div>
</body>
</html>
This should get you what you want, provided the script runs at the end of the document. For wrapping, it keys off of the class title-wrap.
<html>
<head></head>
<body>
<h3>This is a product - title</h3>
<h3 class="title title-wrap">This is a product - with a wrapped title</h3>
<h3>This is a product - with another title</h3>
<script>
(function() {
var titles = document.querySelectorAll('h3');
titles.forEach(function(o, i) {
var title = o.innerHTML;
if (/title-wrap/ig.test(o.className)) {
o.innerHTML = title.replace(/-/g, '<br />');
} else {
o.innerHTML = title.replace(/-.*$/g, '');
}
});
})();
</script>
</body>
</html>
I am trying to change the color of elements that are only within the <code> tag but does not work.
I dont want to use document.GetElementByID as per the answers here getElementsByTagName in JavaScript
Below is my original code.
<div id="wmd-post">
<code>
<p></span></p> <!-- i would want only this to change color -->
</code>
<p></span></p> <!-- i would NOT want this to change color -->
</div>
<script>
var text = document.getElementById("wmd-post");
var str = text.innerHTML;
str = str.replace(/<\/span>/g, '<span style="color:red"></span></span>');
document.getElementById("wmd-post").innerHTML = str;
</script>
What i have tried is
<div id="wmd-post">
<code>
<p></span></p>
</code>
<p></span></p>
</div>
<script>
var text = document.getElementsByTagName('code');
var str = text.innerHTML;
for(var i = 0; i < str.length; i++)
{
str[i] = str.replace(/<\/span>/g, '<span style="color:red"></span></span>');
document.getElementsByTagName("code").innerHTML = str[i];
}
</script>
Please check this fiddle Click Here
You just have to change a Script of your code , Here is the script.
var text = document.getElementsByTagName('code');
var str = text[0].innerHTML;
str = str.replace(/<\/span>/g, '<span style="color:red"></span></span>');
document.getElementsByTagName("code")[0].innerHTML = str;
Your question had the jQuery tag before it was edited away by another user. In case you want to use jQuery, here is one solution.
$(document).ready(function() {
$("#wmd-post > code").css("color", "red");
});
Check out the JSFiddle
I still don't know why you're not using css, but here goes:
html:
<div id="wmd-post">
<code>
<p></span></p>
</code>
<p></span></p>
</div>
JS:
var text = document.getElementsByTagName('code')[0];
var str = text.innerHTML;
str = str.replace(/<\/span>/g, '<span style="color:red"></span></span>');
document.getElementsByTagName("code")[0].innerHTML = str;
Fiddle: https://jsfiddle.net/u8ystwyg/1/
A css only solution:
<style>
code { color: red; }
</style>
<div id="wmd-post">
<code>
<p></span></p>
</code>
<p></span></p>
</div>
document.getElementsByTagName returns a NodeList, not a single element. You need to loop over the list.
var codes = document.getElementsByTagName('code');
for (var i = 0; i < codes.length; i++) {
var str = codes[i].innerHTML;
str = str.replace(/<\/span>/g, '<span style="color:red"></span></span>');
codes[i].innerHTML = str;
}
<div id="wmd-post">
<code>
<p></span></p>
</code>
<p></span></p>
</div>
Here a working example using Element.getElementsByTagName() which basically gets all elements in the document with the specified tag (in your case code tag). You can replace the "target" string using String.prototype.replace() .
(function(){
var text = document.getElementsByTagName('code'),
str = text[0].innerHTML;
str = str.replace(/<\/span>/g, '<span class="red"></span></span>');
text[0].innerHTML = str;
})();
.red{
color:red;
}
<div id="wmd-post">
<code>
<p></span></p>
</code>
<p></span></p>
</div>
I want to remove rich text from my contenteditable div keep only newline or br tags when paste something from clipboard.
I'm trying but its doesn't work
http://jsfiddle.net/marco83/zkf5jkqu/
<div id="editableDiv" contentEditable="true" style="min-height: 200px; border: solid 1px #0099FF;"></div>
<input type="button" value="remove" onclick="strip();">
<script>
function strip() {
var mydiv = document.getElementById("editableDiv");
var str = mydiv.innerHTML;
str = str.replace(/<br>/gi, "\n");
str = str.replace(/<(?:.|\s)*?>/g, "");
mydiv.innerHTML = str;
}
</script>
I copy the text from this page http://www.jacklmoore.com/autosize/
I know it doesn't have any <br> tag the text. but how can i do like Twitter does like this? Thanks.
Try This
<script>
function strip() {
var mydiv = document.getElementById("editableDiv");
var str = mydiv.innerHTML;
mydiv.innerHTML = remove_tags(str);
}
function remove_tags(html) {
html = html.replace(/<br>/g, "$br$");
html = html.replace(/(?:\r\n|\r|\n)/g, '$br$');
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
html = tmp.textContent || tmp.innerText;
html = html.replace(/\$br\$/g, "<br>");
return html;
}
</script>
Example Here
So what i am doing is, i am replace <br> and \n with a placeholder $br$ so as to preserve them and then i am removing all the HTML tags from the string and replacing $br$ back with <br>
Is there an easy way to convert HTML code, that is structured in a certain way, to a single string (that can then be used in a Javascript variable). The new lines and tabs in the html code need to be converted to \n and \t so that the formatting can stay in tact.
example HTML:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Title</h1>
<h2>Subtitle</h2>
<p>Some text goes here</p>
</body>
</html>
I've converted this manually to this:
<html>\n\n\t<head>\n\t\t <title>Hello World</title>\n \t</head>\n\n \t<body>\n \t\t<h1>Title</h1>\n \t\t\t<h2>Subtitle</h2>\n \t\t\t\t<p>Some text goes here</p>\n \t</body>\n\n </html>\n
Is there an easy way to do this automatically? Because I need to convert larger chunks of HTML to this format. Thanks.
function format(data) {
var returnStr = "";
var lines = data.split("\n");
var block = [];
for (var i = 0; i < lines.length; i++) {
block = lines[i].split('\t');
for (var j = 0; j < block.length; j++) {
returnStr += block[j];
if (block.length>1) {
returnStr += "\\t";
}
};
returnStr += "\\n";
};
return returnStr;
}
If you are doing this to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.
<span style="white-space: pre-line">CommentText</span>