Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
DontVoteMeDown Avatar asked Jun 17 '26 15:06

DontVoteMeDown


2 Answers

Just use a capturing group:

"SELECT a, b, c, d FROM".replace(/(SELECT)(.+?)(?= FROM)/, "$1 count(*)")
like image 79
georg Avatar answered Jun 20 '26 05:06

georg


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/

like image 25
Rahul Tripathi Avatar answered Jun 20 '26 04:06

Rahul Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!