0

If I have a string between 2 square brackets that I have created on a page, how would I go about storing that value in a variable and deleting the square brackets?

Example

[String I want]

So I'm left with

var mystring = "String I want"

UPDATE: It appears I can't reply to any of you. SO must be acting up. Anyway this is what I am using

var wholeParagraph = $('.comment-body p');

  var rating = wholeParagraph.substring(wholeParagraph.indexOf('['), 1+wholeParagraph.lastIndexOf(']'));

  alert(rating);

Doesn't seem to work?

4
  • Is the string somewhere within the document? Commented Jun 16, 2009 at 18:15
  • 2
    Keith: replace var wholeParagraph = $('.comment-body p'); with var wholeParagraph = $('.comment-body p').text(); - as it is right now you are merely fetching the jQuery collection, not the actual text inside the paragraph. Commented Jun 16, 2009 at 18:38
  • @Paolo, that will work but if you try running replacements on text() then you'll run into problems if there are other elements within the paragraph. para.html( para.text().replace('[...]','') ); // Elements within the paragraph will be removed... Commented Jun 16, 2009 at 18:53
  • I think the assumption by the way the question is phrased is that that is not the case, though... Commented Jun 16, 2009 at 19:30

6 Answers 6

3

Here's a version that will also handle any leading or trailing whitespace (as well as nested brackets):

// This works
var str = "[String I want]";
var mystring = str.substring(str.indexOf('['), 1+str.lastIndexOf(']'));

// But it'll also work with these strings:
var str = "    [String I want]    ";     // returns "String I want"
var str = " [string I [really] want]  "; // returns "String I [really] want"
Sign up to request clarification or add additional context in comments.

Comments

1
"[String I want]".replace(/^\s*\[|\]\s*$/g, '');

That should give you what you're looking for. You could also use a trim function to take the first and last characters off of the string, similar to PHP's trim, where you can give an optional delimiter.

UPDATED: Leading and trailing whitespace tolerant

Comments

0

I would prefer Andrew Noyes answer. I cannot upvote and make clear that this is better than other, so here is another possibility to get the string you want..

str = str.substr(1, str.length -2);

Comments

0

There's only one reliable way of doing this: Stepping through the DOM and searching for a match in each text node.

This function will do just that:

function findTextNodeWithMatch(regex, context) {

    context = context || document.documentElement;

    var childNodes = context.childNodes,
        retTextNodes = [],
        i = -1, node;

    while ( node = childNodes[++i] ) {
        if (node.nodeType === 3) {
            var m;
            while (m = regex.exec(node.data)) {
                retTextNodes.push({
                    node: node,
                    match: m
                });
            }
        }
        if (node.nodeType === 1 && node.nodeName.toLowerCase() !== 'script') {
            retTextNodes = retTextNodes.concat( arguments.callee( regex, node ) );
        }
    }

    return retTextNodes;

}

Usage:

var patternToMatch = /\[((?:\\\[|.)*)\]/g;
var matchingNodes = findTextNodeWithMatch( patternToMatch, $('.comment-body p')[0] );

for (var i = 0, len = matchingNodes.length; i < len; i++) {
    // Loop through the matching nodes:

    // Extract the string you want:
    var theMatch = matchingNodes[i].match;
    var myString = theMatch[1];
    alert( myString );

    // Replace the string within the node:
    var theNode = matchingNodes[i].node;
    theNode.parentNode.replaceChild( document.createTextNode(theNode.data.replace(patternToMatch, '')), theNode );

}

Using an element's innerHTML is not reliable since it may contain other elements and those elements may have attributes that match what you're looking for - you don't want to remove them by mistake...

Comments

0

Combining the comments and other answers...

var rating = $('.comment-body p').html().replace(/^\[\]$/g, '');
alert(rating);

Comments

-1

Use the string object slice() method to remove first and last chars:

str = str.slice(1,-1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.