replace first occurrence of string after another string - javascript

Tried to find it in the network without any success..
Let's say I have the following string:
this is a string test with a lot of string words here another string string there string here string.
I need to replace the first 'string' to 'anotherString' after the first 'here', so the output will be:
this is a string test with a lot of string words here another anotherString string there string here string.
Thank you all for the help!

You don't need to add g modifier while replacing only the first occurance.
str.replace(/\b(here\b.*?)\bstring\b/, "$1anotherString");
DEMO

If you are looking for something which takes in a sentence and replaces the first occurrence of "string" after "here" (using the example in your case),
You should probably look at split() and see how to use it in a greedy way referring to something like this question. Now, use the second half of the split string
Then use replace() to find "string" and change it to "anotherString". By default this function is greedy so only your first occurrence will be replaced.
Concatenate the part before "here" in the original string, "here" and the new string for the second half of the original string and that will give you what you are looking for.
Working fiddle here.
inpStr = "this is a string test with a lot of string words here another string string there string here string."
firstHalf = inpStr.split(/here(.+)?/)[0]
secondHalf = inpStr.split(/here(.+)?/)[1]
secondHalf = secondHalf.replace("string","anotherString")
resStr = firstHalf+"here"+secondHalf
console.log(resStr)
Hope this helps.

Related

Remove Unfinished String with Ellipsis using regex

I'm trying to remove the String with Ellipsis from unfinished sentences/words not any sentence with Ellipsis:
1. String ... String
2. String String Str...
3. String string String ...
4. String Strin... String
5. String String ... Stri==...
Output:
1. String ... String
3. String string String ...
My first thought was trying to iterate each sentence, but I think regex would be better(wayy better).
Is that possible with regex?
if so How come? I tried few regex unsuccessfully.
Any help will be appreciate.
ps: I can't post the actual strings (company policies), that's why I posted these dummy examples.
Edit:
I've tried regex like:
/(\.*)\.\.\./mgi (I'm not an expert)
but will fail in some cases...
I will retrieve each sentence in an array of String, not a huge and messy String.
Well basically anything with unfinished word or sentence I need to discart. (anything with a word or a single character infront of a Ellipsis)
I assume an invalid sentence always have a word with ... immediately after.
In the regex below, you could put anything that actually separate your words. For now, I put . and (space character).
var str = `1. String ... String
2. String String Str...
3. String string String ...
4. String Strin... String
5. String String ... Stri==...`;
var cleaned = str.split('\n').filter(function (line) {
return !line.match(/[^\. ]+\.{3}/);
}).join('\n');
console.log(cleaned);
/*
prints
1. String ... String
3. String string String ...
*/
Yes it is, you are basically looking for [any character 1 or more times][...], which would be in regexp:
\w+\.{3}
This is assuming that Ellipsis is always 3 dots, if it's not you can do \.+ instead. Use that to find the sentences you want to remove, then keep the other items.

Replace all occurrences of character except in the beginning of string (Regex)

I'm trying to get rid of all minuses/dashes in a string number, except the first occurrence. After fiddling with Regex (JavaScript) for half an hour, still no results. Does anyone know the fix?
Given:
-123-45-6
Expected:
-123456
Given:
789-1-0
Expected:
78910
This one will do as well(it means dashes not at the beginning of the string):
(?!^)-
Example:
text = "-123-45-6".replace(/(?!^)-/g, "");
A simple solution :
s = s.replace(/(.)-/g,'$1')
Jutr try with:
'-123-45-6'.replace(/(\d)-/g, '$1');

Cut out, and replace a part of a string

There is a part in my string from, to which I would like to replace to an another string replace_string. My code should work, but what if there is an another part like the returned substring?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
For example:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
the str should be "abcezzxy"
What you want to do is simple! Cut out and replace the string. Here is the basic tool, you need scissor and glue! Oops I mean string.Split() and string.Replace().
How to use?
Well I am not sure if you want to use string.Split() but you have used string.Replace() so here goes.
String.Replace uses two parameters, like this ("one", "two") what you need to make sure is that you are not replacing a char with a string or a string with a char. They are used as:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
Your code:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
What you should do will be to split the code first, and then replace the second a letter! As you want one in your example. Thats one way!
First, split the string! And then replaced the second a letter with z.
For String.Replace refer this: http://www.w3schools.com/jsref/jsref_replace.asp
For String.SubString: http://www.w3schools.com/jsref/jsref_substring.asp
For String.Split: http://www.w3schools.com/jsref/jsref_split.asp
Strings are immutable. This means they do not change after they are first instantiated. Every method to manipulate a string actually returns a new instance of a string. So you have to assign your result back to the variable like this:
str = str.replace(str.substring(from, to), replace_string);
Update: However, the more efficient way of doing this in the first place would be the following. it is also less prone to errors:
str = str.substring(0, from) + replace_string + str.substring(to);
See this fiddle: http://jsfiddle.net/cFtKL/
It runs both of the commands through a loop 100,000 times. The first takes about 75ms whereas the latter takes 20ms.

Delete a string in javascript, without leaving an empty space?

I've seen multiple instance of that kind of question, but not the one I'm looking for specifically... (I just hope I'm not hopelessly blind ! :P)
Let's consider this code:
var oneString = "This is a string";
document.write(oneString.replace("is", ""));
I would have assumed that the output would have been:
This a string.
But this is the output I'm getting:
This a string
It's like replace() think that the second argument sent is " " and not ""... What would be the proper manner then to strip the string of a given string, without having extra spaces floating in my output ?
You are actually getting "is" replaced with an empty string, it's the space before and after the "is" you replace that stay around as the two spaces you see. Try;
oneString.replace("is ", "")
Are you sure you're not getting "This a string"?
I think you should replace "is " with "" to get your desired output. There is a space before as well as after the word.
Look at the original string - "This_is_a_string" (I replaced spaces with underscores). When you remove "is", you don't touch either of the surrounding spaces, so both end up in the output. What you need to do is oneString.replace("is","").replace(/ +/," ") -- get rid of "is" and then eliminate any double spaces. If you want to keep some double spaces, try oneString.replace(" is","") instead, though you will run into issues if the string starts with is (eg "is it safe?").
The best answer might be something like oneString.replace(/is ?/,"") to match is possibly followed by a space oroneString.replace(/ ?is ?/," ") to match is possibly surrounded by spaces, and replace all of them with one space.
You didn't include any spaces in your pattern. When I try your code in Chrome I get:
> "This is a string".replace("is","")
"Th is a string"
One way to accomplish what you're trying would be to use a regexp instead:
> "This is a string".replace(/is\s/,"")
"This a string"
var aString = "This is a string";
var find = "is"; // or 'This' or 'string'
aString = aString.replace(new RegExp("(^|\\s+)" + find + "(\\s+|$)", "g"), "$1");
console.log(oneString);
The only case where this isn't perfect is when you replace the last word in the sentence. It will leave one space at the end, but I suppose you could check for that.
The g modifier is to make the replace replace all instances, and not just the first one.
Add the i modifier to make it case insensitive.
If you also want this to work on strings like:
"This has a comma, in it"
Change the regexp to:
var find = "comma";
new RegExp("(^|\\s+)" + find + "(\\s+|$|,)", "g")

Reversing a string

I want to reverse a string, then I want to reverse each word in it. I was able to reverse the string. But couldn't reverse words in it.
Given Str = "how are you"
Expected Result = "you are how"
My code
var my_str="how are you";
alert(my_str.split('').reverse().join(''));
Result I get: uoy era woh
How to get the final result??
the other answers are entirely correct if your string has only 1 space between words.
if you have multiple spaces between words, then things are a bit different:
to get just the words, in reverse order, rejoined by 1 space:
str.split(/\s+/).reverse().join(" ")
to reverse the entire string, and still have the original whitespace:
str.split(/\b/).reverse().join('')
the first one uses a regex, "/\s+/", to match an entire run of spaces, instead of a single space. it rejoins the words with a single space.
the second one uses a regex, "/\b/", to just split on the boundaries between words and non-words. since the runs of spaces will be preserved, it just rejoins with an empty string.
I think you've got an empty string in there: my_str.split('')
Make sure you put a space: my_str.split(' ')
The problem is you are splitting with the empty string instead of the space character. Try this:
var str = "how are you";
alert(str.split(" ").reverse().join(" "));
Try it here.
If you are using ES6 then you could use this -
let myStr="How are you";
console.log([...myStr].reverse().join(''));

Categories