How to remove part of string that is in parentheses? - javascript

I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?

Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);

You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo

const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());

Related

JS turn a multi-line string into an array (each item= a line)

For example, I have:
var str = "Hello
World"
I'm expecting an array like that : array["Hello", "World"]
I looked for a method that does that but nothing, I tried to make a loop but I don't know on what I should base my loop? From my knowledge there's not a .length property for the amount of lines in a string...
Use the split function:
var str = `Hello
World`;
var splittedArray = str.split(/\r?\n/);
console.log(splittedArray)
First thing is that the input string is not valid. It should be enclosed by backtick not with a quotes and then you can replace the new line break with the space and then split it to convert into an array.
Live Demo :
var str = `Hello
World`;
const replacedStr = str.replace(/\n/g, " ")
console.log(replacedStr.split(' '));

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...

How to get substring from string after last seen to specific characer in javascript?

I want to get substring from string at last index match space and put it into another string :
for example
if I have : var string1="hello any body from me";
in string1 I have 4 spaces and I want to get the word after last spaces in string1 so here I want to get the word "me" ...
I don't know number of spaces in string1 ... so How I can get substring from string after last seen to specific characer like space ?
You could try something like this using the split method, where input is your string:
var splitted = input.split(' ');
var s = splitted[splitted.length-1];
var splitted = "hello any body from me".split(' ');
var s = splitted[splitted.length-1];
console.log(s);
Use split to make it an array and get the last element:
var arr = st.split(" "); // where string1 is st
var result = arr[arr.length-1];
console.log(result);
Or just :
var string1 = "hello any body from me";
var result = string1.split(" ").reverse()[0];
console.log(result); // me
Thank's to reverse method
I'd use a regular expression to avoid the array overhead:
var string1 = "hello any body from me";
var matches = /\s(\S*)$/.exec(string1);
if (matches)
console.log(matches[1]);
You can use split method to split the string by a given separator, " " in this case, and then get the final substring of the returned array.
This is a good method if you want to use other parts of the string and it is also easily readable:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator
var splitString = string1.split(" ");
// get the last substring from the array
var lastSubstr = splitString[splitString.length - 1];
// this will log "me"
console.log(lastSubstr);
// ...
// oh i now actually also need the first part of the string
// i still have my splitString variable so i can use this again!
// this will log "hello"
console.log(splitString[0]);
This is a good method without the need for the rest of the substrings if you prefer to write quick and dirty:
// setup your string
var string1 = "hello any body from me";
// split your string into an array of substrings with the " " separator, reverse it, and then select the first substring
var lastSubstr = string1.split(" ").reverse()[0];
// this will log "me"
console.log(lastSubstr);

Remove String Between Substring from RegExp

I write this code for remove string from 'a' to 'c'
var str = "abcbbabbabcd";
var re = new RegExp("a.*?c","gi");
str = str.replace(re,"");
console.log(str);
The result in console is "bbd"
But the result that right for me is "bbabbd"
Can I use Regular Expression for this Problem ?
Thank for help.
a(?:(?!a).)*c
Use a lookahead based regex.See demo..*? will consume a as well after first a.To stop it use a lookahead.
https://regex101.com/r/cJ6zQ3/34
EDIT:
a[^a]*c
You can actually use negated character class as you have only 1 character.
The g means it's a global regexp, meaning it picks up both the abc and abbabc in the string. So this does properly remove the items from a..c. It seems you saw only two abc and missed the abbabc. The result bbd is actually correct as it does indeed "remove string from 'a' to 'c'".
abcbbabbabcd => bbd
Here is one more way.
var str = "abcbbabbabcd";
var str= str.replace(/abc/g, "");
console.log(str);
You need to update your regex to a[^ac]*?c , this will avoid character a and c between a and c
var str = "abcbbabbabcd";
var re = new RegExp("a[^ac]*?c","gi");
str = str.replace(re,"");
console.log(str);

Replace a substring with javascript

Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))

Categories