Gorge
Gorge

Reputation: 1399

How to substring in jquery

How can I use jquery on the client side to substring "nameGorge" and remove "name" so it outputs just "Gorge"?

var name = "nameGorge"; //output Gorge

Upvotes: 119

Views: 324031

Answers (8)

Jean G.T
Jean G.T

Reputation: 1

How about the following?

<script charset='utf-8' type='text/javascript'>
  jQuery(function($) { var a=$; a.noConflict();
    //assumming that you are using an input text 
    //  element with the text "nameGorge"
    var itext_target = a("input[type='text']:contains('nameGorge')");
    //gives the second part of the split which is 'Gorge'
    itext_target.html().split("nameGorge")[1];
    ...
  });
</script>

Upvotes: -1

aaronofleonard
aaronofleonard

Reputation: 2576

Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.

http://www.w3schools.com/jsref/jsref_substr.asp The substr function will allow you to extract certain parts of the string.

Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well. http://www.w3schools.com/jsref/jsref_IndexOf.asp

The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?

Upvotes: 0

user113716
user113716

Reputation: 322492

Using .split(). (Second version uses .slice() and .join() on the Array.)

var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer

Using .replace().

var result = name.replace('name','');

Using .slice() on a String.

var result = name.slice( 4 );

Upvotes: 52

user372551
user372551

Reputation:

var name = "nameGorge";
name.match(/[A-Z].*/)[0]

Upvotes: 2

Maurizio Cucchiara
Maurizio Cucchiara

Reputation: 895

You don't need jquery in order to do that.

var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);

Upvotes: 5

drew
drew

Reputation: 1312

Standard javascript will do that using the following syntax:

string.substring(from, to)

var name = "nameGorge";
var output = name.substring(4);

Read more here: http://www.w3schools.com/jsref/jsref_substring.asp

Upvotes: 18

casablanca
casablanca

Reputation: 70701

That's just plain JavaScript: see substring and substr.

Upvotes: 9

Justin Niessner
Justin Niessner

Reputation: 245429

No jQuery needed! Just use the substring method:

var gorge = name.substring(4);

Or if the text you want to remove isn't static:

var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');

Upvotes: 237

Related Questions