Donkey Shame
Donkey Shame

Reputation: 764

Does an element contain a specified string (pure JS)?

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

Answers (5)

Martin Parenteau
Martin Parenteau

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

Andrew Willems
Andrew Willems

Reputation: 12458

  • Convert the desired string into a regular expression.
  • Retrieve all paragraphs (modified as desired using querySelectorAll selectors).
  • Iterate through all the paragraphs.
  • For each paragraph, get the text and search it with the regular expression.
  • If there is a match, add it to an accumulating list of "hits".

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

can.
can.

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

Citrullin
Citrullin

Reputation: 2321

  1. 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

KWallace
KWallace

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

Related Questions