2

How can I remove spaces, a keyword, and everything after it? Here's what I'm looking for

var test = $('.replaceMe').attr('title').replace(/ /g, '');

<a class="replaceMe" href="#" title="Replace By Everything After It">haha</a>

resulting in:

test = Replace;

UPDATE:

The keyword is a yet-to-be-determined word that will be included in all titles. In this example, it is "By".

Both Roko and user1215106's answers work- in that they remove all the excess from the example, leaving Replace, but I failed to clarify that the phrase before the keyword (in this case, Replace) will vary and will have differing amounts of words.

For example:

title="Replace By Everything After It"

Result= Replace

title="All This Should Stay By Things That Should Go"

Result= AllThisShouldStay
3
  • 2
    what do you mean by "keyword"? Commented Jun 26, 2012 at 0:50
  • Do you want to retrieve the first word of the title attribute as a string? Commented Jun 26, 2012 at 0:50
  • mvbl fst: clarified post to explain. Sime Vidas: kind of sort of, clarified above Commented Jun 26, 2012 at 1:12

3 Answers 3

1

jsFiddle demo

var keyword = 'By';

var test = $('.replaceMe').attr('title').split(keyword)[0].replace(/ /g, '') ; 


Or instead of having the keyword variable you can do:

var test = $('.replaceMe').attr('title').split('By')[0].replace(/ /g, '') ; 
Sign up to request clarification or add additional context in comments.

4 Comments

not quite, i'll elaborate above. the phrase before "by" (or whatever the keyword ends up being) varies.
@technopeasant so... (in your 2. example) your keyword is actually the word By, right?
@technopeasant :) there you go! I reedited my answer and the demo
@technopeasant so actually you were very close, you just missed this: .split('By')[0]
1
var test = $('.replaceMe').attr('title').replace(/\s+by\s.*/, '').replace(/\s+/. ''); 

1 Comment

same as Roko- not quite, i'll elaborate above. the phrase before "by" (or whatever the keyword ends up being) varies.
0

Let key be the keyword you want to find.

escapedKey = key.replace(/([-$^&*()\/\\+?.\[\]{}|])/g, "\\$1");
$('.replaceMe').attr('title').replace(new RegExp(escapedKey + ".*"), "")

I tried to generalize for arbitrary keyword, but not yet tested for everything.

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.