How can i make a certain word bold in javascript? [duplicate] - javascript

This question already has answers here:
How to add bold text using javascript
(3 answers)
Closed 1 year ago.
So i have this array of question written in js. And i access to my html using this:
const questionIndex = availableQuestion[arrayReady[currentPage-1]];
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;
how can i make a certain word like = "not","except" from currentQuestion.q bold?

You need a list of words to be bolded, iterate over them, find them in currentQuestion.q, and then bold them.
const currentQuestion = {}
currentQuestion.q = "This is not a not really except good question."
console.log(currentQuestion.q)
const boldWords = ["not", "except"]
boldWords.forEach(word => {
currentQuestion.q = currentQuestion.q.replace(new RegExp("(" + word + ")", "g"), makeBold("$1"))
})
console.log(currentQuestion.q)
function makeBold(str) {
// your bold implementation
return str.bold()
}

I viewed all the answers, but I have developed a more browser compatible code compared to the already existing answers. Please have a look below.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a string in bold.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
const str = "Hello Javesh, How are you doing today?"; //your question
const result = str.split(" ");
const keywords = ["Hello", "How"]; // your keywords
for(var i = 0; i<result.length; i++){
if(keywords.includes(result[i])){
document.querySelector("#demo").innerHTML += "<b>"+result[i]+"</b>"+" ";
}else{
document.querySelector("#demo").innerHTML +=result[i]+" ";
}
}
}
</script>
</body>
</html>
The bold() function is depreciated as its functionality can vary per browser.
Here's the MDN reference for the bold() function:-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold

You could use the bold() function and combine it with a loop and conditions

You could use bold() <- (that's a function) and use it with loops/conditions

Related

document.getElementById("id").innerHTML doesn't work but console.log does. Why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I designed a piece of code where a function is used to make the input to uppercase. When I have the result I output it through console.log where it works perfectly but when I tried to use document.getElementById("SomeId").innerHTML = output; it doesn't work.
I am running Deepin Linux (based on Debian) and am using Visual Studio Code with node.js and npm installed.
function up(name) {
this.name = name.toUpperCase();
};
var nm = prompt("Type in your name in a jumble of capital and lowercase letters!");
var out = new up(nm);
//this works
console.log(out.name);
//this doesn't
document.getElementById("uppercase");
<h1 id="upppercase">Hey</h1>
<p id="smallcase"></p>
I would expect the same output as console.log();
Your code is a bit confused.
1) Your h1 accidentally has the id upppercase with 3 ps in it
2) Your up() function assigns the variable to this, which doesn't make sense
3) You have to use .textContent = ... to put text into a DOM node
Try this:
function up(name) {
return name.toUpperCase();
};
var nm = prompt("Type in your name in a jumble of capital and lower case letters!");
var out = up(nm);
var h1 = document.querySelector("#uppercase");
h1.textContent = out;
<!DOCTYPE html>
<html>
<head>
<title>Prototype</title>
</head>
<body>
<h1 id="uppercase">Hey</h1>
<p id="smallcase"></p>
<script src="script.js"></script>
</body>
</html>
It's because in this line:
document.getElementById("uppercase");
You're not doing anything. You're not actually modifying the DOM. You ned to use innerHTML:
function up(name) {
this.name = name.toUpperCase();
};
var nm = prompt("Type in your name in a jumble of capital and lower case letters!");
var out = new up(nm);
console.log(out.name);
document.getElementById("upppercase").textContent = out.name;
<h1 id="upppercase">Hey</h1>
<p id="smallcase"></p>
Your h1 and an id of upppercase (3 p's) and your code tries to find uppercase.
Also, you don't need a constructor function with new and this here.
Lastly, you must set the content of the h1 to be its old content plus a space and the new output. You were just getting a reference to the element, but not doing anything with that reference.
function up(name) {
return name.toUpperCase();
};
var nm = prompt("Type in your name in a jumble of capital and lower case letters!");
// Concatenate the name to the extisting text in the H1
document.getElementById("uppercase").textContent += " " + up(nm);
<h1 id="uppercase">Hey</h1>
<p id="smallcase"></p>
If you really wanted to use a constructor function so that you could have an object with methods, this would be more appropriate:
// Constructor functions are named using Pascal Case by convention
function Up(name) {
// Create two methods for the object
this.makeUpper = function() { return name.toUpperCase(); };
this.makeLower = function() { return name.toLowerCase(); };
};
var nm = prompt("Type in your name in a jumble of capital and lower case letters!");
// Make an instance:
let myCaseMaker = new Up(nm);
// Use the object and concatenate the name to the extisting text in the H1
document.getElementById("uppercase").textContent += " " + myCaseMaker.makeUpper();
document.getElementById("smallcase").textContent += " " + myCaseMaker.makeLower();
<h1 id="uppercase">Hey</h1>
<p id="smallcase"></p>

trying to find words that begin with a

I am writing some code to find words in paragraphs that begin with the letter "a". I was wondering if there was a shortcut that I could put inside of a variable. I do know about the startsWith() function but that does not work for what i'm trying to do. Here's what I have so far. I'm trying to use the match method and .innerText to read the paragraphs.
function processText() {
var totalNumberOfWords = document.getElementById('p')
var wordsBegginingWithA = 0;
var wordsEndingWithW = 0;
var wordsFourLettersLong = 0;
var hyphenatedWords = 0;
}
<p><button onClick="processText();">Process</button></p>
<p id="data"></p>
<p>The thousand injuries of Fortunato I had borne as I best could; but when he ventured upon insult, I vowed revenge. You, who so well know the nature of my soul, will not suppose, however, that I gave utterance to a threat.
<span style='font-style:italic;'>At
length</span> I would be avenged; this was a point definitely settled--but the very definitiveness with which it was resolved precluded the idea of risk. I must not only punish, but punish with impunity. A wrong is unredressed when retribution
overtakes its redresser. It is equally unredressed when the avenger fails to make himself felt as such to him who has done the wrong.</p>
You can get the inner text of the p element - split it at the spaces to get the words - pass the words through a function to see if the first letter is "a" and if so, increment a count.
processText();
function processText() {
var p = document.querySelector('p').innerText;
var totalWords = p.split(' ');
var wordsBegginingWithA = 0;
totalWords.forEach(function(word){
if ( beginsWithA(word) ) {
wordsBegginingWithA++
};
})
console.log(wordsBegginingWithA); // gives 5
}
function beginsWithA(word){
return word.toLowerCase().charAt(0) == 'a';
}
<p>Apples and oranges are fruit while red and blue are colors</p>
You can use:
[variablename].match(/(?<!\w)a\w*/ig)!=null? a.match(/(?<!\w)a\w*/ig).length:0; to detect what words starting with what letter (in example it was a).
And:
[variablename].match(/\S+/g)!=null? a.match(/\S+/g).length:0;
to detect word count.
function processText() {
var a = document.getElementById('p').innerText;
var b = a.match(/(?<!\w)a\w*/ig)!=null? a.match(/(?<!\w)a\w*/ig).length:0;
var word= a.match(/\S+/g)!=null? a.match(/\S+/g).length:0;
console.log('Text: ',a,'\nA starting word: ', b, '\nWord count: ',word);
}
processText();
<span id="p">Apple is super delicious. An ant is as good as my cat which favors a pear than fish. I'm going to test them all at once.</span>
Explanation: .match would return all value which matches the expression given.
Notice that I also used conditional (ternary) operator to detect whether or not the Regex will return a null value if no match were returned. If it's returning null then it would result in 0 (:0) if it's returning another value than null then it would return the count (.length).
More info related to Regular expression: https://www.rexegg.com/regex-quickstart.html
function processText() {
let pp = document.getElementById('root')
console.log(pp.innerHTML.match(/(?<!\w)a\w*/g))
return pp.innerHTML.match(/(?<!\w)a\w*/g);
}
processText()
<p id='root'>this is a apple</p>
Using the result of indexOf, 0 is the equivalent to startsWith
var str = document.getElementById("myTextarea").value;
var keyword = document.getElementById("myInput").value;
var n = str.indexOf(keyword);`
Working sample in this fiddle.
HTH

Why is array[0] = array[0].toUpperCase() working, while array[0][0] = array[0][0].toUpperCase() isn't [duplicate]

This question already has answers here:
string.charAt(x) or string[x]?
(7 answers)
Capitalize words in string [duplicate]
(21 answers)
Closed 4 years ago.
TO BE CLEAR:
I don't want to know how to capitalize, but rather I want to know why i can change it in one-dimensional, but not 2-dimensional
I'm doing some coding challenges to get familiar with JavaScript.
I capitalized the first Letter of each word in a given string.
I split the string into a word-seperated array via String.match(regex);
var word_array = str.match(/\w(\w)*/g);
And I then made from the word another letter-seperated array to change single letters. (also with regex)
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
And this works just fine.
But I wanted it a bit shorter, so I tried to do the action on the letter on the second dimension of the word_array, but with no effect at all.
word_array[i][0] = word_array[i][0].toUpperCase();
Full-Code-Snippet
const input = document.querySelector("#string"),
button = document.querySelector("#DOIT");
button.addEventListener("click", function(){
LetterCapitalize(input.value);
});
function LetterCapitalize(str) {
var word_array = str.match(/\w(\w)*/g);
for(let i = 0; i < word_array.length; i++){
//This part works
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
word_array[i] = letter_array.join("");
//this doesn't
/*
word_array[i][0] = word_array[i][0].toUpperCase();
console.log(word_array[i][0]);
*/
}
console.log(word_array);
str = word_array.join(" ");
return str;
}
<input id="string" type="text"/>
<button id="DOIT">DO IT</button>
This wouldnt work wouldn't work since Strings are immutable in javascript. the
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
code snipped worked as you converted your strings to a list/array which is mutable by nature. although, id like to point out that this question might be a duplicate. here is a capitalization in javascript question

my replace is not working in my function? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
var jtj_code_lines = []; // this array will hold all the jtj codes line
var JTJ = function(j){
j = j.replace(" ","");
jtj_code_lines = j.split(';'); // splitting all the lines seperated from ;
for(var i=0; i<jtj_code_lines.length; i++){
if(jtj_code_lines[i].charAt(0) === '*'){ // * means that the following word is the name of a method that will perform some action
var q1 = jtj_code_lines[i].replace('*', ''),
q1_pos_1 = q1.indexOf('['); // find the position of the keyword [
var q1_funcname = q1.slice(0, q1_pos_1); // it find the name of that perticular function
if(q1_funcname === "Message"){ // this checks weather the function name is message
var q1_pos_2 = q1.indexOf(']'), // this ifnds the position of keyword ]
q1_func_value = q1.slice(q1_pos_1+1, q1_pos_2); // this finds what is written inside [] and accepts as the value of Message
alert(q1_func_value);
}else{
}
}
}
};
so the above function is pretty simple it finds the specific text written in the braces, i mean that if you write :
JTJ('*Message[hi];')
then it will alert hi and this is quit simple and this is alerting as expected but the problem is coming that if any * is after white space then that perticular thing is not being alerted, so the following have the same condition,*Message[go ]; starts with whitespace so it is not being alerted :
JTJ('*Message[sanmveg];*Message[saini]; *Message[go ];')
but i have a this line j = j.replace(" ",""); to remove all the white spaces, then why it is not working? is there any other way to do this?
thanks.
Fix: j = j.replace(/\s/gi,"");
this would remove all " " with "", in short it would act as replaceAll.
Before it was just replacing first matched " " with "".

How to detect image file extension in a string with JavaScript [duplicate]

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 9 years ago.
I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.
Use lastIndexOf()
var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);
Fiddle
You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.
'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]
var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];
Try this.
function searchText(text)
{
var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/");
for (var i=0; i<arr.length; i++)
{
//Make tags where 'arr[i]' is your url.
}
}
HINT: (Please use logic based on your needs)
you have to split string somehow based on your condition and check if the string has . or something
var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' ');
if text array has your condition then assign to variable filename
if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}
separate the extension
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}

Categories