Categories
JavaScript Answers

How to Find the Position Index of a Regex Match Result in JavaScript?

Sometimes, we want to find the index of the regex match in our JavaScript code.

In this article, we’ll look at how to find the index of a regex match with JavaScript.

Use the RegExp.prototype.exec Method

We can use the JavaScript regex’s exec method to find the index of a regex match.

For instance, we can write:

const match = /bar/.exec("foobar");  
console.log(match && match.index);

We call exec on /bar/ with 'foobar' as the argument to find the bar pattern in the 'foobar' string.

If match isn’t null , then it should have the match.index property with the first index of the matched substring in the 'foobar' string.

Since 'bar' starts at index 3, match.index should be 3.

We can also use it to get the index of all the matches in a string.

For instance, we can write:

const re = /bar/g,  
  str = "foobarfoobar";  
while ((match = re.exec(str)) !== null) {  
  console.log(match && match.index);  
}

re has the g flag to let us search for all the matches of a pattern in a string.

We loop through the results returned by re.exec with the while loop.

If the returned result isn’t null , then we keep getting the matched results until it returns null .

match.index therefore should be 3 and 9 since the first 'bar' starts at index 3 and the 2nd 'bar' starts at index 9.

Conclusion

We can find the indexes of one or more matches of a regex pattern within a JavaScript string by using the RegExp.prototype.exec method.

Categories
JavaScript Answers

How to Select an HTML Element by their textContent Value with JavaScript?

Sometimes, we want to select an HTML element by their textContent value with JavaScript.

In this article, we’ll look at how to select an HTML element by their textContent value with JavaScript.

Select Elements with document.querySelectorAll and Loop Through Them to Find the Ones We Want

We can select multiple elements with document.querySelectorAll .

Then we can loop through them to find the ones we want with the for-of loop.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

Then we can the div with text ‘bar’ by writing:

const divs = document.querySelectorAll("div");
const searchText = "bar";

for (const div of divs) {
  if (div.textContent.includes(searchText)) {
    console.log(div.textContent)
  }
}

We select all the divs with document.querySelectorAll .

Then we loop through each item with the for-of loop.

In the loop body, we check if div.textContent includes the searchText with the includes method.

If it does, then we log it with console log.

Therefore, we should see the console log log 'bar' as a result.

Search for an Element with the Given Text Content by XPath

Another way to search for an element with the given text content is to use an XPath.

For instance, if we have the following HTML:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz

Then we can the div with text ‘bar’ by writing:

const xpath = "//div[contains(text(),'bar')]";
const matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(matchingElement)

using the xpath string.

xpath is a string that specifies we match the div elements that contains the text ‘bar’.

Then we can use the xpath string to search for the element we want by calling the document.evaluate method with the xpath as the first argument.

document is the 2nd argument which means we’re search the whole document for the element.

singleNodeValue returns the first element node that matches the XPath we’re using to search.

Therefore, matchingElement should be the div element with text content ‘bar’.

Conclusion

We can search for an element with the given text content by selecting elements and looping through them to find it.

Or we can search for it with an XPath.

Categories
JavaScript Answers

How to Add Options to an HTML select Element with JavaScript?

Sometimes, we want to add options to an HTML select element with JavaScript.

In this article, we’ll look at how to add options to an HTML select element with JavaScript.

Using the document.createElement Method

We can use the document.createElement method to create a new option element.

Then we can call appendChild on the select element to append it as a child of the select element.

For instance, we can write the following HTML:

<select>

</select>

to create an empty select element.

Then we can add the option elements for the select element by writing:

const select = document.querySelector('select')
const arr = ['apple', 'orange', 'grape']
for (const [index, a] of arr.entries()) {
  const opt = document.createElement('option');
  opt.value = index;
  opt.innerHTML = a;
  select.appendChild(opt);
}

We get the select element with document.querySelector .

Then we define the arr array with the option text we want to add.

Next, we have a for-of loop to loop through the arr entries.

We call arr.entries to return an array with the index and the value of the array entry each in their own array.

In the loop body, we call document.createElement to create the option element.

Next, we set the value property to set the value of the value attribute of the option element.

Then we set the innerHTML property to set the content that the user sees in the drop-down for each option.

And finally, we call select.appendChild with the opt element object to add it as a child of the select element.

Therefore, now we should see a drop-down with apple, orange, and grape as options.

Conclusion

We can add options into the select HTML element with the document.createElement method.

Then we can append the created option element to the select element with appendChild .

Categories
JavaScript Answers

How to Join or Combine Two JavaScript Arrays by Concatenating Them into One Array?

Sometimes, we want to combine 2 JavaScript arrays by concatenating them into one array.

In this article, we’ll look at how to join or combine 2 JavaScript arrays by concatenating them into one array.

Use the Array.prototype.concat Method

One way to join 2 Javascript arrays by concatenating them into one array is to use the JavaScript array’s concat method.

For instance, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = a.concat(b);
console.log(c)

We call a.concat(b) to add the entries of b after the entries of a and return the new array with all the entries.

Therefore, c is:

["a", "b", "c", "d", "e", "f"]

Use the Spread Operator

Another way to combine 2 arrays by joining them together is to use the spread operator.

For example, we can write:

const a = ['a', 'b', 'c'];
const b = ['d', 'e', 'f'];
const c = [...a, ...b]
console.log(c)

We spread the entries of a and b into a new array to form the c array.

They’ll be spread in the same order that they’re listed.

Therefore, c is now:

["a", "b", "c", "d", "e", "f"]

Conclusion

We can use the JavaScript array’s concat method or the spread operator to combine 2 JavaScript arrays by joining them together.

Categories
JavaScript Answers

How to Remove an Element from a JavaScript Array with Lodash?

Sometimes, we want to remove an element from a list with Lodash.

In this article, we’ll look at how to remove an element from a JavaScript array with Lodash.

Use the remove Method

One way to remove an element from a JavaScript array is to use the Lodash remove method.

For instance, we can write:

const obj = {
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [{
    "subTopicId": 1,
    "number": 1
  }, {
    "subTopicId": 2,
    "number": 32
  }, {
    "subTopicId": 3,
    "number": 22
  }]
}
const stToDelete = 2;
_.remove(obj.subTopics, {
  subTopicId: stToDelete
});
console.log(obj)

to remove the obj.subTopics entry with the subTopicId set to 2.

To do this, we call the remove method with the obj.subTopics property as the first argument.

And we pass in an object with the entry with the subTopicId we want to delete from obj.subTopics .

The removal operation will be done in place.

And the removed item will be returned.

Therefore, obj is now:

{
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [
    {
      "subTopicId": 1,
      "number": 1
    },
    {
      "subTopicId": 3,
      "number": 22
    }
  ]
}

Instead of passing in an object as the 2nd argument of remove , we can also pass in a predicate function with the condition of the items we want to remove.

To do this, we write:

const obj = {
  "objectiveDetailId": 285,
  "objectiveId": 29,
  "number": 1,
  "text": "x",
  "subTopics": [{
    "subTopicId": 1,
    "number": 1
  }, {
    "subTopicId": 2,
    "number": 32
  }, {
    "subTopicId": 3,
    "number": 22
  }]
}
const stToDelete = 2;
_.remove(obj.subTopics, (currentObject) => {
  return currentObject.subTopicId === stToDelete;
});
console.log(obj)

We call remove with the same first argument.

But the 2nd argument is replaced with a predicate function that returns the condition of the object we want to remove.

And so e get the same result as in the previous example.

Conclusion

We can remove an element from an array in an object with Lodash with the remove method.