HumphreyBogart
HumphreyBogart

Reputation: 11

Remove part an ever-changing text string with javascript?

I have a string of text "AB-123-2011-07-09", and need to remove everything except "123", then add a "#" sign to the end result.

The string "123" is ever increasing in number, as is the "2011-07-09" (a date). Only "AB" stays the same.

So the end result would be: #123

Is this possible?

Thanks.

EDIT: Just to clarify, I was needing a script that could globally search a page and replace any text which had the format of "AB-xxx-xxxx-xx-xx" with just the digits highlighted here in bold, then adding the "#" before it.

Currently there are only 3 digits in that position, but in the future there may be four.

My code:

function Replace() {
var OldString = "AB-123-2011-07-09";
var NewString = OldString.replace(/^AB-(\d+)-.*/, "#$1");
document.body.innerHTML = document.body.innerHTML.replace(OldString, NewString);
}
window.onload = Replace();

So far it only replaces 1 instance of the string, and uses a fixed string ("AB-123-2011-07-09").

What regular expression do I need to make the 'OldString' dynamic, rather than it being fixed as it is now?

Upvotes: 1

Views: 228

Answers (4)

migg
migg

Reputation: 1

This is of course possible. This regex would do the trick:

“AB-123-2011-07-09“.replace(/^AB-(\d+)-\d+-\d+-\d+$/, “#$1“);

It also checks you given syntax and that there is nothing else in the string.

migg

Upvotes: 0

Garett
Garett

Reputation: 16838

The following regex would work, but in this case I don't think you need a regex at all (as @Eric has already shown).

"AB-123-2011-07-09".replace(/^AB-(\d+)-.*/, "#$1");

This results in the value #123

http://jsfiddle.net/3XhbE/

Upvotes: 1

Eric Fortis
Eric Fortis

Reputation: 17360

var data = "AB-123-2011-07-09";
var field = data.split('-')[1];
document.write("#" + field);

http://jsfiddle.net/efortis/8acDr/

Upvotes: 3

Jon Lin
Jon Lin

Reputation: 143936

Does this work?

var result = mystring.replace(new RegExp(AB-([0-9]+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9], "g"),"#$1");

mystring is the "AB-123-2011-07-09" string and result would be "#123".

Upvotes: 0

Related Questions