Reputation: 764
Given this:
<p>knownString-randomString</p>
How do I find all paragraphs in a document that contain "knownString-," using pure JavaScript only?
For each instance of <p>knownString-randomString</p>
, I need to split "knownString-randomString" at the hyphen(-
) and store "randomString" in a variable for later use.
Thanks.
Upvotes: 1
Views: 1197
Reputation: 73761
Here is one way:
function FindRandomStrings()
{
var allParagraphs = document.getElementsByTagName("p");
var regex = /knownString-(.*)/;
var result = [];
var match;
var i;
for (i = 0; i < allParagraphs.length; i++)
{
match = regex.exec(allParagraphs[i].innerHTML);
if (match)
{
result.push(match[1]);
}
}
return result;
}
Upvotes: 1
Reputation: 12458
querySelectorAll
selectors).var knownString = "knownString";
var regex = new RegExp(knownString + "\\-(.*)");
var pars = document.querySelectorAll("p");
var results = [];
[].forEach.call(pars, function(par) {
var x = par.firstChild.nodeValue.match(regex);
if (x) results.push(x[1]);
});
alert(results);
<p>something else</p>
<p>knownString-randomString1</p>
<p>knownString-randomString2</p>
Upvotes: 0
Reputation: 2259
var randomStrings = [];
var ps = document.querySelectorAll('p');
for(var i = 0; i < ps.length; i++) {
if(ps[i].textContent.startsWith('knownString')) {
randomStrings.push(ps[i].textContent.split('-')[1]);
}
}
The variables you need would be stored in randomStrings
Upvotes: 0
Reputation: 2321
Get your elements
var paragraphs = document.getElementsByTagName('p');
2. For loop with check and split your string
for(var i = 0; i < paragraphs.length; i++){
if(paragraphs[i].innerHTML.search('knownString') > -1){
randomString = paragraphs[i].innerHTML.split('-')[1];
}
}
Upvotes: 1
Reputation: 1700
If your paragraphs are inside some other element, either a div, or ultimately the <body>
, you can select those with jQuery $('divID p'), iterate through them, and use split() to separate the known and unknown strings into an array.
var ArrayElement = split("knownString-randomString");
ArrayElement(0) will have your knownString, and ArrayElement(1) will have your randomString.
Upvotes: 0