How to replace last substring of a string in javascript? [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I want to replace the last substring of a string without splitting the whole string. Exp: "I am a newbie" to "I am a student". But this piece of code not working. Please, help!
var old = "newbie"
var new_ = "student"
var str = str.replace(new RegExp(old + '$'), new_);

Your code is working. But you had not declared the str variable with the value "I am a newbie". You directly tried to replace, which may have caused it to not work.
var old = "newbie"
var new_ = "student"
var str = "I am a newbie"
str = str.replace(new RegExp(old + '$'), new_);
console.log(str)

A more general answer, if you want to replace the last word of the input string by another value, but you do not know what that word will be beforehand, you can use a regular expression.
string.replace(/\w+$/, 'student');
const strings = [
'I am a newbie',
'I like sunshine',
'I do not like pheasants'
];
strings.forEach(e => {
console.log(`Updated ${e} to ${e.replace(/\w+$/, 'student')}`);
});

Related

Remove a specific string from the beginning of a string? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
My code:
var pathname = window.location.pathname;
//output of pathname is "/removethis/page/removethis/color.html"
var string = "/removethis/";
if (pathname.match("^"+string)) {
pathname = preg_replace(string, '', pathname);
}
alert(pathname);
The output is:
I try to find out if the beginning of the string is a match to /something/ and if yes, then remove this string from the beginning of "pathname";
What I expect is:
page/removethis/color.html
But I get the error
preg_replace is not defined
You could use RegExp to do this in one go
var pathname = "/removethis/page/removethis/color.html";
var string = "/removethis/";
var regex = new RegExp("^" + string);
console.log(pathname.replace(regex,""));
You need to use .replace() in JavaScript, preg_replace() is for PHP.
Try this :
pathname = pathname.replace(string, '')
You need to remove the quotes from around your regex.
var pathname = "/removethis/page/removethis/color.html";
//output of pathname is "/removethis/page/removethis/color.html"
var regex = /^\/removethis/;
if (pathname.match(regex)) {
pathname = pathname.replace(regex, '');
}
alert(pathname);

Javascript - Regex Does not contain some character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I try to regex for not contain some character.
I need to show /%7(.*?);/g which dose not contain "=".
I try to input
?!xx=1
and change to
?!( (.?)=(.?) )
But it dose not work.
Please help. Thanks.
//Here is my simple regex
reg = /%7((?!xx=1).*?);/g ;
//Here is my string
str = "%7aa; %7bb=11; %7cc=123; %7xx=1; %7yy; %7zz=2;"
//I need
%7aa; and %7yy;
Instead of using a negative lookahead, try using a ^ block:
const reg = /%7([^=;]+);/g;
The ([^=;]+) bit matches any non-=, the condition you're looking for, and non-;, the character at the end of your regex.
I left the capture group in since your question's regex also contains it.
const reg = /%7([^=;]+);/g;
const str = "%7aa; %7bb=11; %7cc=123; %7xx=1; %7yy; %7zz=2;"
const matches = str.match(reg);
console.log(matches);

How to escape special charater in javascript's Variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I might asking a naive question.
But I am stuck. My requirement is do masking of data.
Following is the code snippet :
var str = substr(Test_dat,0,6);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
So basically, "Test_dat" is input string and I am applying substr() function the on incoming data. And then replacing based on masking logic.
If
var Test_dat = "Vikas(vikas)";
var str = substr(Test_dat,0,5);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
Output
SampleSample(vikas)
If
Input
var Test_dat = "Vikas(vikas)";
var str = substr(Test_dat,0,6);
var Test_dat1 = replace(Test_dat,str,"SampleSample");
Error Message
Function call replace is not valid : Unclosed group near index 6
I know it's because of '(' but I am not able to understand how to escape in variable "str".
Any Help!!
Change the way you use substr and replace. This code works well.
var Test_dat = "Vikas(vikas)";
var str = Test_dat.substr(0,6);
var Test_dat1 = Test_dat.replace(str,"SampleSample");

Get all values between '[ ]' on a string with JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How are you guys doing?
I'd like to ask today if you could help me with a tricky question that I was unable to solve on my own.
I [have] strings that [are] like this.
I was looking for a way to get "have" and "are" and form an array with them using JavaScript. Please notice that this is an example. Sometimes I have several substrings between braces, sometimes I don't have braces at all on my strings.
My attempts focused mostly on using .split method and regex to accomplish it, but the closest I got to success was being able to extract the first value only.
Would any of you be so kind and lend me an aid on that?
I tried using the following.
.split(/[[]]/);
You can use the exec() method in a loop, pushing the match result of the captured group to the results array. If the string has no square brackets, you will get an empty matches array [] returned.
var str = 'I [have] strings that [are] like this.'
var re = /\[([^\]]*)]/g,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ 'have', 'are' ]
Note: This will only work correctly if the brackets are balanced, will not perform on nested brackets.
var str = "I [have] strings that [are] like this";
var res = str.split(" ");
The result of res will be an array with the values:
I
[have]
strings
that
[are]
like
this
If you want to get only values between braces, you can use the following regex expression:
var str = "I [have] strings that [are] like this";
var result = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((result = pattern.exec(str)) != null)
{
result.push(match[1]);
}
This is JSFiddle example for you.
Simple as this:
'I [have] strings that [are] like this.'.match(/\[([^\]]*)]/g)

Replace method in javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to replace a string in javascript using regex but not able to do it. What I am trying is:
var str = [{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]
str.replace(/"\\{/g,"\\{") // replace every instance of "{ with just {
I want to replace all instance of "{ with just { and all instance of }" with just }. How can I do 2 replacement together and where I am going wrong in 1 replacement as the replacement that I am using is not actually happening.
Escape { with \ once. Escaping in the replacement string is not necessary.
str.replace(/"\{/g,"{")
// "[{"Contact":[{"name":"abc","address": "xyz","PhoneNumber": "08976"}", {"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}",{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]"
BTW, str in the question is not a string literal.
You can do both replacement in single replace call:
var repl = str.replace(/"(\{)|(\})"/g, '$1$2');
Make sure str is a valid string
You can use built-in JSON parsing to avoid use of regex
If you meant the string to be an actual string...
// Be sure that it's a string
var str = '[{"Contact":["{"name":"abc","address": "xyz","PhoneNumber": "08976"}", "{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}","{"name":"abc","address": "xyz","PhoneNumber": "08976"}"]}]';
// Assign the output to a variable and use single backslash to escape `{`. You're
// using the literal regex construct here / ... /
result = str.replace(/"(\{)|(\})"/g,"$1$2");
And to replace both "{ to { and }" to }, you can use capture groups, backreferences and an "or" regex operator (|).
jsfiddle

Categories

Resources