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

I am trying to replace everything with a space after a question mark.

Suppose I have a line as shown below:

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

Now I want to replace everything with an empty one after ?.

Expected Result: "/root/Users"

I tried the solution below:

 var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, ""); console.log(str); // output : ? str = str.split('?')[0] // though worked but not readable 

I do not want to use a loop for this . Is there a better way to do this?

+8
javascript
source share
6 answers

This should help

 var str = "/root/Users?SkillId=201;" str = str.replace(/\?.*$/g,""); console.log(str); 
+15
source share

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

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

+5
source share

Align the contents to ?

 var str = "/root/Users?SkillId=201;" var a = str.match(/(.*)\?/); console.log(a[1]) 
+3
source share

Just use the 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/

+3
source share

var str = "/root/Users?SkillId=201;" var parts = str.split('?', 2);

parts [0] contains the line before '?'

+2
source share

Solution without using Regular Expression ;

pseudo code

 Find the index location of the '?' character, if the resulting index is greater than -1; then; extract the new string; starts at index 0 to the nth index location of the '?' character 

JS code

 // get the index of the first occurrence of '?' var qMarkIndex = str.indexOf('?'); // '?` character exist if(qMarkIndex > -1) str = str.substr(0, qMarkIndex); console.log(str); 

Adding a conditional statement that checks if a character exists ? , guarantees; if for some reason the character str does not contain the character ? then the string remains unchanged.

+1
source share

All Articles