Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace everything with blank after question mark in a string?

Tags:

javascript

I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?

like image 834
Learning-Overthinker-Confused Avatar asked Jul 07 '17 10:07

Learning-Overthinker-Confused


4 Answers

This should help

var str = "/root/Users?SkillId=201;"

str = str.replace(/\?.*$/g,"");
console.log(str);
like image 116
Nagaraju Avatar answered Oct 20 '22 00:10

Nagaraju


Another option is to get the substring before the '?':

str = str.substr(0, str.indexOf('?'));

like image 43
tony Avatar answered Oct 19 '22 23:10

tony


Match the content before ?

var str = "/root/Users?SkillId=201;"
var a = str.match(/(.*)\?/);

console.log(a[1])
like image 32
prasanth Avatar answered Oct 20 '22 01:10

prasanth


Simply use JavaScript function

var str = "/root/Users?SkillId=201;";
var str = str.substring( 0, str.indexOf("?")-1 );
console.log(str);

here is the fiddle: https://jsfiddle.net/ahmednawazbutt/2fatxLfe/3/

like image 37
ahmednawazbutt Avatar answered Oct 19 '22 23:10

ahmednawazbutt