views:

745

answers:

6

Howdy,

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?

A: 

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

str = str.slice(1,-1);
Tehnomaag
+1  A: 
"[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

Andrew Noyes
A: 

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);

Tammo
+2  A: 

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"
Triptych
A: 

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

J-P
A: 

Combining the comments and other answers...

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