DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Replace text between two words

This question seems to be simple and repetitive here in SO.

But consider this string: SELECT a, b, c, d FROM. I want to get only what is between SELECT and FROM.

Nice so I have found this answer that propose this regex: (?<=SELECT)(.*)(?=FROM). It's perfect if lookbehind works in JavaScript, according to this post:

Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax

So it won't work(test it in regexpal that is made for JS). This anwser proposes this regex: SELECT=(.*?)FROM. But it includes the two words, so it not fits my needs.

The purpose of this is to use in a replace function to transform this...

SELECT a, b, c, d FROM

into this...

SELECT Count(*) FROM

Thank you in advance.

Upvotes: 2

Views: 7933

Answers (5)

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

Try this:-

$("button").click(function() {
var srctext = $("#fixme").text();
console.log("old text: " + srctext);

var newtext = srctext.replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)");
console.log("new text: " + newtext);

$("#fixme").text(newtext)
});

WORKING JSFIDDLE:- http://jsfiddle.net/tkP74/1597/

Upvotes: 2

Fuzzley
Fuzzley

Reputation: 306

Without regex:

var query = "SELECT a, b, c, d FROM";
var iSelect = query.indexOf("SELECT");
var selLen = "SELECT".length;
var iFrom = query.indexOf("FROM");
if (iSelect >= 0 && iFrom >= 0) {
    query = query.replace(query.substring(iSelect + selLen, iFrom), " COUNT(*) ");
    console.log(query);
}

Upvotes: 1

georg
georg

Reputation: 214949

Just use a capturing group:

"SELECT a, b, c, d FROM".replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)")

Upvotes: 7

Jason McCreary
Jason McCreary

Reputation: 72971

Just as an alternative to regular expressions for this specific string:

str = 'SELECT COUNT(*) ' + str.substr(str.indexOf('FROM'));

Upvotes: 1

Jerry
Jerry

Reputation: 71538

Well, you can just put the SELECT back like I said in my comment:

str.replace(/SELECT (.*?)(?= FROM)/i, "SELECT Count(*)");

Upvotes: 1

Related Questions