Wrap words with &nbsp in span [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I need wrap words with &nbsp in span, for example:
<p>Word word and word2? But word word to.</p>
Should become:
<p>Word <span>word and word2?</span> But word <span>word to.</span></p>
I wanna do this with regular expression in JavaScript.

You can do something like this https://regex101.com/r/bUflp4/2 for you regex. Be care however, it won't accept tag inside others.
For the replacement, you can use something like this
var elements = document.getElementsByClassName("text-to-replace");
for (var i = 0; i < elements.length; i++) {
var innerHTML = elements.item(i).innerHTML;
var regex = new RegExp('([^ ,<]* [^ ,<\/]*)', 'ig');
var text = innerHTML.replace(regex, '<span class="span-to-add">$1</span>');
elements.item(i).innerHTML = text;
}
.span-to-add {
background-color: yellow;
}
<div class="container">
<p class="text-to-replace">Word word and word2? But word word to.</p>
<p class="text-to-replace"> word this is an example</p>
<p class="text-to-replace">this is another example</p>
</div>

Related

How to place a variable inside getElementbyId() that changes during each repetition of a loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want something similar to f" {variable} " of python
Ive tried
function press()
{
for(var i=0; i<4; i++)
{
if(!document.getElementById('ip'+i).value)
{
alert("error");
break;
}
}
but it didnt work.
I want something similar to f" {variable} " of python
template strings ${variable}
In JavaScript you can use template strings
The usage is
` ${variable} `
document.getElementById('btn').addEventListener('click', press)
function press() {
for (var i = 0; i < 4; i++) {
if (!document.getElementById(`ip${i}`).value) {
alert("error");
break;
}
}
}
<input id="ip0"/>
<input id="ip1"/>
<input id="ip2"/>
<input id="ip3"/>
<button id="btn">Click</button>

Split plain text from img tag using javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a api response that is a combination of plain text and image tag. What is the best way to separate plain text from the response? I need to separate plain text so I can style it separately.
This is the example of a response:
This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />
You can use regex to remove html tag like this
str = str.replace(/<(?:.|\n)*?>/gm, '');
or you this if only remove image tag str = str.replace(/<img .*?>/g, '');
var str = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
//str = str.replace(/<(?:.|\n)*?>/gm, '');
str = str.replace(/<img .*?>/g, '');
console.log(str);
One approach might be to use the following regular expression /<img[\s\w=\":/.-]+>/gmi to match and replace the <img /> tag in your response string:
const responseText = `This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />`
const responseWithoutImageTag = responseText.replace(/<img[\s\w=\":/.-]+>/gmi, '')
console.log(responseWithoutImageTag)
A safer way than regular expressions is to parse the HTML and extract the text content:
var template = document.createElement('template');
template.innerHTML = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />';
template.content.textContent returns 'This is the cap you unscrew to open when you refuel your car '
You can use substring from o to index of image tag
var str = 'This is the cap you unscrew to open when you refuel your car <img alt="blah" src="https://www.lifesure.co.uk/cms/wp-content/uploads/2011/04/Tyre-Illustration-500.jpg" />'
var newStr = str.substring(0, str.indexOf('<img'));
console.log(newStr)
Simply put, you could do this:
const textOnly = str.slice(0, str.indexOf('<img'));
If you want the image tag only:
const imageTag = str.slice(str.indexOf('<img'), str.length);
(substring works too, like in the answer by Syed)

Need Help: Make the quiz random [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

javascript split string by pattern [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i want to split this string in JavaScript.
i try it:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "<new_a><new_b><sb_c>";
var res = str.split("<");
document.getElementById("demo").innerHTML=res;
}
</script>
</body>
</html>
result:
new_a> , new_b> , sb_c>
i want to my result : new_a , new_b , sb_c
how can i do?
function myFunction()
{
var str = "<new_a><new_b><sb_c>";
str = str.replace("<","");
str = str.replace(">"," ");
var res = str.split(" ");
document.getElementById("demo").innerHTML=res;
}
Try this code.

represent and stylize xml code in html [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Showing XML code in an HTML page could be difficult.
XML tags will be recognized as HTML tags, so they will be not showed as they should.
Escaping the angular brackets <> works, but then the xml code will be showed all in black, difficult to read. Is there a way to stylize XML code in an HTML page, as I would read it in an XML editor?
Here's my javascript function that changes style to xml-key-words!!
(unfortunately it doesn't indent xml)
It accepts plain XML text as input, and return HTML styled code, with xml as text, coloring
XML keywords with different colors as in an editor.
function stylizeXML(xml)
{
xml = xml.replace(/>/g,"&gt");
xml = xml.replace(/</g,"&lt");
xml = xml.replace(/\&gt\&lt/g, "&gt <br> &lt"); // >< becomes > <br> <
var greens=xml.match(/<(\S+\s+)+[\S]+\=\"[^>]+>/g); // ...=
for (i=0; i<greens.length; i++)
{
greens=xml.match(/\s+\S+\=\"/g);
for (i=0; i<greens.length; i++)
{
green = greens[i];
green = green.replace(/\=\"/g, '=</span>"');
attributes = green.match(/\s+\S+\=<\/span>\"/g);
for(j=0; j<attributes.length; j++)
{
attribute2 = "<span class='color_green'>"+attributes[j];
green = green.replace(attributes[j], attribute2);
}
xml = xml.replace(greens[i], green);
}
}
var blues=xml.match(/\&lt(.*?)\&gt/g); // < ... >
for (i=0; i<blues.length; i++)
{
blue = blues[i];
blue = blue.replace("&lt/","");
blue = blue.replace("&lt","");
blue = blue.replace("&gt","");
if (blues[i].match(/^\&lt\//))
// </ ... >
{xml = xml.replace(blues[i], "<span class='color_orange'>&lt/</span><span class='color_blue'>"+blue+"</span><span class='color_orange'>&gt</span>");} // </
else
// < ... >
{xml = xml.replace(blues[i], "<span class='color_orange'>&lt</span><span class='color_blue'>"+blue+"</span><span class='color_orange'>&gt</span>");}
}
var reds=xml.match(/\=<\/span>(\s*)\"(.*?)\"/g); // ="..."
for (i=0; i<reds.length; i++)
{
red = reds[i];
red = red.replace("=</span>","");
xml = xml.replace(reds[i], "=</span><span class='color_red'>"+red+"</span>");
}
return xml;
}
here's the CSS associated:
<style type="text/css">
.color_orange
{color :rgb(255,96,24);}
.color_blue
{color :blue;}
.color_red
{color :rgb(234, 49, 176);}
.color_green
{color : rgb(72,150,163);}
</style>

Categories